-1

Using Angular 7:

I'm using ngFor to bind an Array of objects to rows in a table. Immediately after pushing a new row I need to call another function which requires that new row having been rendered, but the rendering process is (i assume) asynchronous with my code, so the next function executes and cannot find the new row.

How do i wait for Angular to finish updating?

  • 3
    Please post some code snippet. – hrdkisback Nov 26 '19 at 10:17
  • Share some code! What you have done so far? – Surjeet Bhadauriya Nov 26 '19 at 10:17
  • When asking a question, people will be better able to provide help if you provide code that they can easily understand and use to reproduce the problem. [mre] – Mukyuu Nov 26 '19 at 10:18
  • 1
    Have you tried using [setTimeout(0)](https://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful) hack? Just wrap your function - the one you need to call after the row gets inserted - inside a setTimeout(0) and see if that helps. – Nicolae Olariu Nov 26 '19 at 10:27
  • @NicolaeOlariu It works! Is this a fairly standard practice with Angular then? I would have thought this would be a fairly common issue. If you post your comment as an answer i will mark it as the solution. Thanks. – india_tango Nov 26 '19 at 10:42
  • It doesn't have anything to do with Angular, it deals with the JavaScript single-threaded architecture. `setTimeout(0)` just adds a new event to the call stack. Meanwhile, the event loop asks for the message queue, requesting the next event to be processed. That's why your function will get executed immediately after browser's engine empties the current call stack. – Nicolae Olariu Nov 26 '19 at 11:06
  • Sorry - my comment was poorly worded. I understand why setTimeout works in this instance; i'm surprised, however, as i ran into this problem almost immediately when i started learning angular, and i don't see it mentioned in any beginner - oriented angular tutorials. – india_tango Nov 26 '19 at 11:15

1 Answers1

2

Please wrap your function inside a setTimeout(fnHere, 0) expression. Doing this, the browser will just execute your fn immediately when it breathes a bit (immediately after finished rendering - your code will be queued up until the Browser's engine empties the current call stack).

Nicolae Olariu
  • 2,487
  • 2
  • 18
  • 30
  • Hi Nicolae, setTimout() - Is this right way of doing it..? Is it going to cause any issues in future in the angular app..? – Mounica Apr 28 '22 at 06:30