How to wait for DOM to render

1.1k Views Asked by At

I have to wait for DOM to render before going into next functions. Here is the flow/lifecycle:

  1. Push into the Array:
    this.someFormArray.push((this.createForm({
      name: 'Name'
      type: type,
    })))
  1. Trigger functions that are trying to access HTML from step 3.
    this.onSizeChange();
  1. 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.

1

There are 1 best solutions below

4
On

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