![](/img/trans.png)
[英]Angular4 Change Detection ExpressionChangedAfterItHasBeenCheckedError
[英]Angular change detection error: ExpressionChangedAfterItHasBeenCheckedError
當組件內部的輸入綁定值從null / undefiend更改為某個值時,出現此錯誤。 以下是示例代碼的URL。
https://stackblitz.com/edit/angular-h61csi
為什么會出現此錯誤? 有人請向我解釋如何在沒有setTimeout的情況下解決此問題。
您可以將設置this.selectedItem
放在setTimeout
。
setTimeout(() => {
if(!this.selectedItem) {
this.selectedItem = this.items[1];
this.cdr.markForCheck();
}
});
要知道為什么以及何時發生此錯誤,您可以在此處閱讀有關ExpressionChangedAfterItHasBeenCheckedError
-https: //blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasenenedederror-error-error-e3fd9ce7dbb4
完全同意@vatz響應,並進行了較小的校正。 我們不需要'this.cdr.markForCheck()',僅當我們在組件中使用了onpush更改檢測時才需要它。
setTimeout(() => {
if(!this.selectedItem) {
this.selectedItem = this.items[1];
}
});
我認為解決問題的最佳方法是重新設計組件。 您的子組件不應將值傳遞回父組件,尤其是如果父組件已經知道值是什么,即您的AppComponent確切知道selectedItem和items數組的值是什么,那么您可以將子組件的AfterViewInit掛鈎中的邏輯放在父組件中。 只需將selectedItem字段更改為:
private _selectedItem: Object;
public get selectedItem() {
return this._selectedItem ? this._selectedItem : this.items[1];
}
然后從子組件中的AfterViewInit掛鈎中刪除代碼,一切都應該正常工作。 否則,您將不得不使用setTimeout。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.