简体   繁体   中英

Angular change detection error: ExpressionChangedAfterItHasBeenCheckedError

I am getting this error when input binding value is changed inside the component from null/undefiend to some value. Below is the URL for sample code.

https://stackblitz.com/edit/angular-h61csi

Why do I get this error? Someone please explain me how to resolve this without setTimeout.

You can put setting this.selectedItem in a setTimeout .

setTimeout(() => {
  if(!this.selectedItem) {
    this.selectedItem = this.items[1];
    this.cdr.markForCheck();
  }
});

To know why and when this error occurs you can read about ExpressionChangedAfterItHasBeenCheckedError here - https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4

Totally agree with @vatz response with small correction. We don't need 'this.cdr.markForCheck()', its required only when we have onpush change detection used in the component.

setTimeout(() => {
  if(!this.selectedItem) {
    this.selectedItem = this.items[1];
  }
});

I think the best way to resolve your issue is to redesign your components a bit. Your child component shouldn't pass values back to the parent component, especially if the parent component already knows what the values are, ie the AppComponent in your case, knows exactly what the values of the selectedItem and the items array are, so you can put the logic from the AfterViewInit hook of the child component in the parent component. Simply change the selectedItem field to:

private _selectedItem: Object;

public get selectedItem() {
    return this._selectedItem ? this._selectedItem : this.items[1];
}

And then remove the code from the AfterViewInit hook in the child component and everything should work without errors. Otherwise, you will have to use setTimeout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM