I have a simple test code for adding dynamic components with Angular 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)
}
}
All this code is doing is adding a dummy template at the end.
But this code throws an Exception :
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 ?
It is well descriptive exception. A view has been updated after already checked for changing.
But there are few things which I don't understand here :
Question(s) :
1:
If I remove the input from the template - so now the template is :
<ng-template #template>
<li></li>
</ng-template>
— Then I don't get an exception. Why is that ?
2:
Another solution(among many) is to replace ngAfterViewInit with ngAfterContentInit. I already know the difference between those two.
If so - can I conclude ( from the fact that the exception is gone) that at each Angualr's event - a change detection is occurred? (which make sense becuase ngAfterViewInit happens _after_ ngAfterContentInit) , so maybe Angular has detected the prev dynamic change in ngAfterViewInit ? Am I right?

<ng-template #anchor? did you intent to use<ng-container?