簡體   English   中英

ExpressionChangedAfterItHasBeenCheckedError`錯誤角度4

[英]ExpressionChangedAfterItHasBeenCheckedError` error angular 4

我正在嘗試一個包含多個組件的項目。 示例應用程序在這里 我處於如下情況,在開發模式中出現錯誤

錯誤

我知道為什么會出現此錯誤

因為綁定子組件值之后,父組件值會由祖父母組件更新,從而導致在角度臟檢查時拋出錯誤

我的應用程序的框架就在這里 有人可以幫我解決這個問題。 我知道可以通過使用setTimeout或changeDetectionRef解決。 但這不是我正在尋找的解決方案,我想知道我在生命周期掛鈎期間做錯了什么。 提前致謝。

很高興聽到您反對setTimeout並手動調用detectChanges

我知道這在您的應用程序結構中很明顯,但這是一個示例,向您顯示錯誤的出處:

https://ng-run.com/edit/d9EEfZLhGfM0fYQtehhs?open=app%2Fgrandparent%2Fparent%2Fchild%2Fchild.component.html&layout=2

因為綁定子組件值之后,父組件值會由祖父母組件更新,從而導致在角度臟檢查時拋出錯誤

看來您是對的,但在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM