1

How do I run code in Angular 2+ after a check cycle was done?

Currently we are using setTimeout, with timing of 1 to achieve this. Isn't there a more readable way to do it?

Our current code looks something like this:

doSomething();
window.setTimeout(() => doSomethingAfterACheckCycle(), 1);

I also know about afterViewChecked, but that is a centralised function for a component, I would need a lot of flags to track cycles. Isn't there an inline way to do it? I only have problem with the notation of setTimeout 1, it makes the code baffling for a junior developer.

We can also create a service call, which internally would use setTimout, I would only like to know if there is already something implemented in Angular for this.

It would also be nice to have linking instead of nesting, something like:

nextCheck(() => soSomething()).nextCheck(() => doSomethingElse());

Edit

We have several scenarios needing this, but an example: We are binding model state to the active/disabled state of tabs. But we also set the selected tab based on url. A problem was changing the model for the tab to become active and also selecting it, did not work on the same change cycle. We had to change the model, which in the next change cycle enabled the tab, then we set is as selected. Another trick here was to manually enable the tab indifferent of the binded (bound?) variable so it would work on the same change cycle.

Máthé Endre-Botond
  • 4,826
  • 2
  • 29
  • 48
  • 1
    May I ask why you need to do this? I have found that whenever I was getting "expression changed after checked" errors, that it was a hint that the flow of my application was not quite right. A little restructuring/refactoring resolved the issue without having to us a timeout or other "after check cycle" hack. – DeborahK Mar 19 '18 at 16:34
  • setTimeout just adds your callback to Callback queue. Think which async function you are waiting for and call `doSomethingAfterACheckCycle()` when its done. – Julius Dzidzevičius Mar 19 '18 at 16:50
  • Possible duplicate of https://stackoverflow.com/questions/34827334/triggering-change-detection-manually-in-angular – Estus Flask Mar 19 '18 at 16:51
  • 1
    Little info, setTimeout with 0 works too ;) – Noémi Salaün Mar 19 '18 at 22:39
  • You should look into https://angular.io/api/core/NgZone#onMicrotaskEmpty observable – Noémi Salaün Mar 19 '18 at 22:40
  • 2
    @estus It's a thing to trigger the change detection and another to run code after the change detection – Máthé Endre-Botond Mar 21 '18 at 12:24

0 Answers0