input and output for the same variable

cucuru picture cucuru · Jul 23, 2018 · Viewed 10.1k times · Source

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?

Answer

Giacomo Vo&#223; picture Giacomo Voß · Jul 23, 2018

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!