0
votes

Trying to get two way binding to work but getting the expression changed after it was checked exception. When mode changes to cancel and I want to reset the value to empty I get the exception. I assume it is because I am emitting inside of a change cycle with a different value but do not know how to avoid?

<edit-field [mode]="mode" [(field)]="field"></edit-field>

My component is:

 export class EditFieldComponent implements OnChanges {
      @Input('mode') mode: string;
      @Input('field') field: string;
      @Output('fieldChange') fieldChange: EventEmitter<string> = new EventEmitter<string>();

     ngOnChanges() {
         if(this.mode == 'cancel'){
         this.field = "";
         this.fieldChange.emit("");
    }
  }
}
1
A way around that is to manually decouple 2-way binding: Bind an Input into the component and bind an Eventemitter in the component to the output, but don't use 'the same one'. That's the cleanest way when wanting 2-way binding to a component that has to manipulate the incoming data. - EluciusFTW

1 Answers

1
votes

Angular doesn't like when change detection causes model changes. ngOnChanges is called by change detection.

Either move the code to another callback that doesn't cause this error (I think ngAfterViewChecked works) or use setTimeout()

 export class EditFieldComponent implements OnChanges {
      @Input('mode') mode: string;
      @Input('field') field: string;
      @Output('fieldChange') fieldChange: EventEmitter<string> = new EventEmitter<string>();

     ngOnChanges() {
         if(this.mode == 'cancel'){
           setTimeout(() => {
             this.field = "";
             this.fieldChange.emit("");
           });
         }
    }
  }
}