4
votes

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?

2
this is newbie error :). don't change the state of the component manually after it was already checked. See stackoverflow.com/q/34364880/573032Roman C
thx guys, will have a look on it. Rusev solved the actual bugVáclav Mikeska

2 Answers

10
votes

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

4
votes

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