I'm building an Angular 4 app with many components where the ChangeDetectionStrategy
is OnPush
. While the Angular Documentation on the matter is void of much information, various sources say that OnPush
components only update when their @Input
s change (new objects or primitives).
However, it seems that various events inside an OnPush
component will also trigger change detection. I'm noticing others do not trigger change detection, however.
What are the specific rules for ChangeDetectionStrategy.OnPush
in regards to events inside a component?
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.
Angular runs its change detection mechanism periodically so that changes to the data model are reflected in an application's view. Change detection can be triggered either manually or through an asynchronous event (for example, a user interaction or an XMLHttpRequest completion).
Async pipe does't trigger changeDetection and do not redraw value in UI.
How is change detection implemented? Angular can detect when component data changes, and then automatically re-render the view to reflect that change.
This blog post of the Angular University contains several indications about the events that trigger change detection when using ChangeDetectionStrategy.OnPush
:
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
They add the following recommendations:
So if we remember to subscribe to any observables as much as possible using the async pipe at the level of the template, we get a couple of advantages:
- we will run into much less change detection issue using OnPush
- we will make it much easier to switch from the default change detection strategy to OnPush later if we need to
- Immutable data and @Input() reference comparison is not the only way to achieve a high performant UI with OnPush: the reactive approach is also an option to use OnPush effectively
In a comment following the question "Change Detection on Angular 2" on Disqus, Viktor Savkin explains:
When using OnPush detectors, then the framework will check an OnPush component when any of its input properties changes, when it fires an event, or when an observable fires an event.
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