Reputation: 785
I am using Angular Material in my Angular 4 app. When I try to use the MatSnackBar
in the ngAfterViewInit()
, I am facing an error as:
ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: 'visible-bottom'.It seems like the view has been created after its parent and its children have been dirty checked. Has it been created in a change detection hook ?
I have used the ChangeDetectorRef
to detect the changes, but it doesn't seem to work.
Here's the code I have been working on:
constructor(private matSnackBar: MatSnackBar, private router: Router, private cdr: ChangeDetectorRef) { }
ngOnInit() {}
ngAfterViewInit() {
let snackBarRef = this.matSnackBar.open('Redirecting to dashboard..', 'Cancel', {
duration: 10000
});
snackBarRef.onAction().subscribe(() => {
console.log("Cancelled");
});
this.cdr.detectChanges();
}
Please help me resolve this issue.
Upvotes: 3
Views: 4435
Reputation: 451
Try to move snackbar in your constructor:
constructor(private matSnackBar: MatSnackBar, private router: Router, private cdr: ChangeDetectorRef) {
let snackBarRef = this.matSnackBar.open('Redirecting to dashboard..', 'Cancel', {
duration: 10000
});
snackBarRef.onAction().subscribe(() => {
console.log("Cancelled");
});
}
Upvotes: 4
Reputation: 483
One potential but crude solution is to use setTimeout -
let snackBarRef;
setTimeout(() => {
snackBarRef = this.matSnackBar.open('Redirecting to dashboard..', 'Cancel', {
duration: 10000
});
});
please refer https://github.com/angular/material2/issues/6158 for more information.
Upvotes: 4