16
votes

I have a variable that can be edited from parent and for child.

parent.html:

 <div *ngIf="editEnabled">
  <mat-icon (click)="disableEdit()">cancel</mat-icon>
</div>

<child [(editEnabled)]="editEnabled"></child>

parent.ts:

export class ParentComponent {

   editEnabled: boolean;

   disableEdit(){
     this.editEnabled = false;
   }
}

Child.html:

 <div *ngIf="!editEnabled">
  <mat-icon (click)="enableEdit()">settings</mat-icon>
</div>

child.ts

private _editEnabled: boolean;

@Input()
 set editEnabled(value: boolean) {
  this._editEnabled = value;

}
get editEnabled(): boolean {
 return this._editEnabled;
}

enableEdit(){
     this.editEnabled = true;
}

But I cant comunicate editEnabled between the two components.

Where is my mistake?

2
angular.io/guide/component-interaction should help you getting started. - Dheeraj Kumar
you must use output decerator in this case - Muhammed Albarmavi

2 Answers

30
votes

When defining a double-binded variable, you will need to define one @Input-decorator with the variable name:

@Input() editEnabled: boolean;

and one @Output-decorator with the variable name and Change after it, because this one emits the changing-event of the variable:

@Output() editEnabledChange: EventEmitter<boolean> = new EventEmitter<boolean>();

Then when changing the variable inside the child component, invoke this.editEnabledChange.emit(true). Your double binding with [(...)] is correct!

12
votes

If you don't want to add the editEnabledChange-Emitter every time you change the variable correct you can write:

_correct: boolean;
@Input()
set correct(val: boolean) {
  this.correctChange.emit(val);
  this._correct = val;
}
get correct() {
  return this._correct;
}
@Output()
correctChange: EventEmitter<boolean> = new EventEmitter<boolean>();
<app-pin [(correct)]="isPinCorrect"></app-pin>