简体   繁体   中英

Angular Material Change Detection using ngOnChanges throwing error, “ExpressionChangedAfterItHasBeenCheckedError”

I have a Input property for a component and I should only display if the current data is not undefined.

I'm using ngOnChanges to detect the changes, but it's throwing " ExpressionChangedAfterItHasBeenCheckedError " error.

Here's the code,

  ngOnChanges(changes: { [propName: string]: SimpleChange}) {
if (changes['message'].currentValue) {
  this.open();
}}


open() {
    let config = new MatSnackBarConfig();
    config.verticalPosition = this.verticalPosition;
    config.horizontalPosition = this.horizontalPosition;
    config.duration = this.setAutoHide ? this.autoHide : 0;
    config.extraClasses = this.addExtraClass ? ['test'] : undefined;
    this.snackBar.open(this.message, this.action ? this.actionButtonLabel : undefined, config);
}

Stackblitz link: https://stackblitz.com/edit/angular-snackbar-top-bdmsmz

Is there any way to resolve the error.

Stackblitz错误消息

This is problem related to the lifecycle events of Angular.

One quick way to fix it is to wrap the misbehaving code, which in this case is the snackBar.open call, in a setTimeout function

setTimeout(()=>{
  this.snackBar.open(this.message, this.action ? this.actionButtonLabel : undefined, config);
})

Demo

Error goes way in this way:

    ngOnChanges(changes: { [propName: string]: SimpleChange}) {
        setTimeout(()=>{
      if (changes['message'].currentValue) {
          this.open();
        }
        })
      }

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