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.
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.
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.
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.
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.”
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With