[英]Angular Error: ExpressionChangedAfterItHasBeenCheckedError
[英]ExpressionChangedAfterItHasBeenCheckedError` error angular 4
很高興聽到您反對setTimeout
並手動調用detectChanges
。
我知道這在您的應用程序結構中很明顯,但這是一個示例,向您顯示錯誤的出處:
因為綁定子組件值之后,父組件值會由祖父母組件更新,從而導致在角度臟檢查時拋出錯誤
看來您是對的,但在ngAfterContentInit發生之前已渲染了子組件。
Angular應用程序是一棵視圖樹。 當角度游程變化檢測機制通過該視圖樹並為每個視圖調用checkAndUpdateView函數。
在執行此功能期間,角度嚴格按定義的順序調用其他功能。 在我們的案例中,我們對以下功能感興趣:
execEmbeddedViewsAction
callLifecycleHooksChildrenFirst (AfterContentInit)
execComponentViewsAction
這意味着angular會在執行ngAfterContentInit
hook之前更早地調用嵌入式視圖( ng-template
生成嵌入式視圖)的更改檢測周期 。 這是您的示例中發生的情況:
如上圖所示,當角度檢查AppComponent視圖時,它將首先檢查嵌入式視圖,然后為GrandParentComponent
調用ngAfterContentInit
,然后進入GrandParentComponent
視圖。
似乎有很多解決方法。 我在這個演示中嘗試了它們
關鍵時刻不是使用ngAfterContentInit
掛鈎,而是在ParentComponent
設置索引和活動值:
parent.component.ts
export class ParentComponent {
private _active: boolean = false;
public index = 0;
constructor(
@Host() @Inject(forwardRef(() => GrandParentComponent))
public grandParentComponent: GrandParentComponent) {
this.index = this.grandParentComponent.parents.length;
this.grandParentComponent.parents.push(this)
}
ngOnInit() {
this.active = this.index == this.grandParentComponent.currentStep;
}
ngOnDestroy() {
if (this.grandParentComponent) {
this.grandParentComponent.parents = this.grandParentComponent.parents.filter(x => x !== this);
}
}
在GrandParentComponent
聲明了GrandParentComponent
屬性的GrandParentComponent
:
grandparent.component.ts
export class GrandParentComponent {
parents = [];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.