简体   繁体   中英

Angular dynamic component loading - ExpressionChangedAfterItHasBeenCheckedError

I need to create instances of multiple components dynamically on the run.

I found several examples on the internet, including StackOverflow and angular.io page itself.

But always receiving exception ExpressionChangedAfterItHasBeenCheckedError when I'm assigning a value to the component model.

Even the dedicated example for this functionality throws the same exception: Angular.io article Plunker

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: 'Bombasto'. 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 ?

Should I just ignore this or it can/should be fixed?

This is because you are altering component state in ngAfterViewInit . See the issue here discussing the behavior.

In your case you can move the initial creating in ngOnInit .

 ngOnInit() {
    this.loadComponent();
    this.getAds();
 }

https://plnkr.co/edit/vAbkBIqrhpuuWadO4zGD?p=preview

In the more general case

use

this._changeDetectionRef.detectChanges();

at the end of the method that did update to late the component state,

... not forgetting to add

private _changeDetectionRef : ChangeDetectorRef

as parameter of the constructor of the Component owning your method.

See discution here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM