I have to wait for DOM to render before going into next functions. Here is the flow/lifecycle:
- Push into the Array:
this.someFormArray.push((this.createForm({
name: 'Name'
type: type,
})))
- Trigger functions that are trying to access HTML from step 3.
this.onSizeChange();
- HTML Renders it:
<ng-container *ngFor="let item of someFormArray.controls">
<img[src]="someUrl">
</ng-container>
And here is the problem, HTML render should be step 2. but thats not how Angular lifecycle works, to battle this I wrapped step 2. into SetTimeout which naturally triggers after DOM render:
setTimeout(() => {
this.onSizeChange();
}, 0);
While this works, I'm interested is there any better way to handle this, or this is fine?
Note: This whole flow is triggered on user change/click, not onInit, AfterViewInit etc.
Use the AfterViewInit lifecycle hook which will call a parent function after he rendered properly.
Put the Step #2 inside the afterViewInit lifecycle hook.
https://angular.io/api/core/AfterViewInit