Issue
I'm learning TemplateRef and ViewContainerRef concepts in Angular 13.3.0.
My component template is very simple:
<ng-container #container></ng-container>
<ng-template #templ let-item="name">
Example {{name}}
</ng-template>
In the component code:
export class MyComponent implements OnInit {
@ViewChild("container", {read: ViewContainerRef})
container!: ViewContainerRef;
@ViewChild("templ", {read: TemplateRef})
templ!: TemplateRef<any>;
constructor() { }
ngAfterViewInit() {
this.container.createEmbeddedView(this.templ, { name: "John" });
}
}
But I get the runtime error:
ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: 'John'. 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?. Find more at https://angular.io/errors/NG0100
What is the correct hook method in which call createEmbeddedView(...) and why is that?
I've already tried ngOnInit and ngAfterContentInit
Thanks
Solution
You should use ngAfterViewInit, and then call this.cd.detectChanges() to update the view after creating the embedded component
cd is a reference to ChangeDetectorRef which you can inject in the constructor
Angular details on ViewChild instantiation and lifecycle hooks
Answered By - Drenai
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.