Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what cases should I use runOutsideAngular if I'm already using OnPush change detection

Tags:

angular

I'm already using OnPush change detection with immutable data. I'm wondering is there further optimizations I can do with my change detection by using ngZone.runOutsideAngular? I'm just looking for some guidelines here.

like image 235
seescode Avatar asked Jul 13 '17 18:07

seescode


People also ask

In which situations will Angular check for changes in a component using the OnPush change detection strategy?

An OnPush change detector gets triggered in a couple of other situations other than changes in component Input() references, it also gets triggered for example: if a component event handler gets triggered. if an observable linked to the template via the async pipe emits a new value.

What is the difference between OnPush and default change detection?

OnPush means that the change detector's mode will be set to CheckOnce during hydration. Default means that the change detector's mode will be set to CheckAlways during hydration.

What is change detection OnPush?

The OnPush strategy changes Angular's change detection behavior in a similar way as detaching a component does. The change detection doesn't run automatically for every component anymore. Angular instead listens for specific changes and only runs the change detection on a subtree for that component.

Which service is used by developers to start change detection resulted by async operation automatically?

NgZone run() and runOutsideOfAngular() js can monitor all the states of synchronous and asynchronous operations, Angular additionally provides a service called NgZone. This service creates a zone named angular to automatically trigger change detection.”


1 Answers

They are not particularly related. OnPush controls change detection on the level of each component, while ngZone "sort of" triggers change detection for the entire application.

Angular uses zones, particularly NgZone to get notified whenever there are no more tasks. A task scheduled in a zone will be executed in this zone. So all async tasks like setTimeout are executed inside NgZone. The ngZone.runOutsideAngular allows you to schedule a task outside ngZone which means that once it's complete Angular will not be notified and no change detection will take place.

If you have some recurring async task that gets executed many times a second (like a mousemove event) then you could probably leverage ngZone.runOutsideAngular to avoid triggering change detection for each event. Then you could schedule a manual change detection once a second. Other than that I can't think of how it can help you optimize the application.

like image 107
Max Koretskyi Avatar answered Oct 23 '22 16:10

Max Koretskyi