![](/img/trans.png)
[英]Angular change detection error: ExpressionChangedAfterItHasBeenCheckedError
[英]Angular Material Change Detection using ngOnChanges throwing error, “ExpressionChangedAfterItHasBeenCheckedError”
我具有组件的Input属性,并且仅在当前数据未定义的情况下才显示。
我正在使用ngOnChanges来检测更改,但是它引发了“ ExpressionChangedAfterItHasBeenCheckedError ”错误。
这是代码,
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链接: https ://stackblitz.com/edit/angular-snackbar-top-bdmsmz
有什么办法可以解决该错误。
这是与Angular的生命周期事件有关的问题。
解决该问题的一种快速方法是将行为不当的代码包装在setTimeout
函数中,在本例中,该代码是snackBar.open
调用
setTimeout(()=>{
this.snackBar.open(this.message, this.action ? this.actionButtonLabel : undefined, config);
})
错误以这种方式进行:
ngOnChanges(changes: { [propName: string]: SimpleChange}) {
setTimeout(()=>{
if (changes['message'].currentValue) {
this.open();
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.