5

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?

3

2 Answers 2

10

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

Sign up to request clarification or add additional context in comments.

4 Comments

Many thanks, this solved issue. Didn't expected bug directly in Angular docs on such a key functionality
Actually it is not a bug, but a intended behavior - very annoying one :).
Currently the official example about dynamic component loading contains that error angular.io/generated/live-examples/dynamic-component-loader/… - this solution applies to that as well
This article shows another method using async update with a microtask: indepth.dev/…
5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.