Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular dynamic component loading - ExpressionChangedAfterItHasBeenCheckedError

Tags:

angular

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?

like image 724
Václav Mikeska Avatar asked Dec 07 '22 18:12

Václav Mikeska


2 Answers

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

like image 153
rusev Avatar answered Dec 10 '22 13:12

rusev


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

like image 42
user1767316 Avatar answered Dec 10 '22 13:12

user1767316