Search code examples
angularangular-forms

Is there a way to wait for the DOM to update in Angular?


If I have something like the following

<form #myForm="ngForm">
  <input *ngFor="let item of items; index as i" [name]="'input_' + i" [(ngModel)]="item" myValidationAttribute>
</form>

and I have a function that updates items and I need to wait form the form to update before submitting the form

updateAndSubmit() {
  this.items = newItems;
  setTimeout(() => {
    if (this.myForm.valid) {
      // Do stuff with valid form
    }
  });
}

Is using setTimeout like this the preferred way of waiting for the DOM refresh or is there something along the line of fixture.whenStable() used in unit testing?

setTimeout just doesn't feel right, like it is a dirty hack.

Here is a StackBlitz https://stackblitz.com/edit/angular-pv4tyb


Solution

  • As @Antediluvian said, this is not a hack, it's about putting the callback onto the end of the event queue, i.e. making sure that the code in the callback doesn't run in the current event loop, but it the next one or later.

    That said, if you find yourself doing something like this, and need to specify a delay in the setTimeout, then you have a problem, because it's unlikely that the delay that you use in development will work for all clients.

    In this case, the simple setTimeout that you are using should be fine, and AFAIK, is "the way that it's done".

    I understand that your actual code is more complex, but based on this example, consider that you don't need to push that extra value through the form - you can just get the value of the form, and modify that directly (or a copy of the form value) to produce the value that you use (for, say, posting to an API).