Reputation: 3735
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.
Upvotes: 3
Views: 2662
Reputation: 568
Error goes way in this way:
ngOnChanges(changes: { [propName: string]: SimpleChange}) {
setTimeout(()=>{
if (changes['message'].currentValue) {
this.open();
}
})
}
Upvotes: 2
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);
})
Upvotes: 2