當我有一個簡單的測試代碼,用於將動態部件與角4.角 - 異常增加動態成分
@Component({
selector: 'component',
template: `
<ul><li #item *ngFor="let number of list">{{number}}</li></ul>
<ng-template #anchor> </ng-template>
<ng-template #template>
<li><input type="text" [(ngModel)]="myInput"/></li>
</ng-template>`
})
class _Component {
@ViewChild('template')
template: TemplateRef<any>
@ViewChild('anchor', { read: ViewContainerRef })
anchor: TemplateRef<any>
@ViewChildren('item', { read: ViewContainerRef })
items: QueryList<ViewContainerRef>
myInput='';
list: number[] = [0, 1, 2, 3, 4]
ngAfterViewInit() {
this.anchor.createEmbeddedView(this.template)
}
}
所有這些代碼正在做的是將在端部具有虛設模板。
但這代碼引發異常:
ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: ''. It seems like the view has been created after its parent and its children have been dirty checked. Has it been created in a change detection hook ?
這是很好的描述例外。已經檢查更改後,視圖已更新。
但是,有一些我不明白這裏幾件事情:
問題(S):
1:如果我從模板中刪除input
- 所以現在的模板是:
<ng-template #template>
<li></li>
</ng-template>
- 然後我不' t得到一個例外。這是爲什麼 ?
2:
另一種解決方案(其中許多)是ngAfterContentInit
取代ngAfterViewInit
。我已經知道這兩者之間的區別。
如果是這樣 - 我可以得出結論(,因爲例外情況已不復存在)在每個Angualr事件中發生變化檢測? (這是有道理的,因爲ngAfterViewInit
發生_after_ ngAfterContentInit
),所以也許Angular已經檢測到ngAfterViewInit
的prev動態變化?我對嗎?
你爲什麼要插入'
@Maximus它並不重要(恕我直言)。 Angular將動態內容添加爲A SIBLING。所以它真的沒關係。 –
我建議你閱讀[你需要知道的關於角度變化檢測的所有內容](https://hackernoon.com/everything-you-need-to-know-about-change-detection-in-angular-8006c51d206f)以及[this](https://hackernoon.com/angulars-digest-is-reborn-in-the-newer-version-of-angular-718a961ebd3e#d14a) –