![](/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.