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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With