Varun
Varun

Reputation: 3735

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 error message

Upvotes: 3

Views: 2662

Answers (2)

Sagar Rana
Sagar Rana

Reputation: 568

Error goes way in this way:

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

Upvotes: 2

Ploppy
Ploppy

Reputation: 15353

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

Upvotes: 2

Related Questions