Angular Change Detection Strategies

Angular provides you two Change Detection Strategies, the defaultone and the onPush.

ChangeDetectionStrategy.Default

In order to know whether the view should be updated, Angular needs to access the new value, compare it with the old one & make the decision on whether the view should be updated.

By default, Angular makes no assumption on what the component depends upon. So it has to be conservative and will check every time something may have changed, this is called dirty checking. In a more concrete way, it will perform checks for each browser's events, timers, XHRs, and promises.

This can be problematic when you’re starting to have a big application with many components, specially if you’re focused on performance.

ChangeDetectionStrategy.onPush

When using the onPush strategy on the component, you basically say to Angular that it should not make any guess on when it needs to perform the check for change. It will rely only on the change of the Input references, some events triggered by itself (the component), or one of its children. Lastly, you, the developer, can ask explicitly Angular to do it with the componentRef.markForCheck() method.

With onPush, the component only depends on its inputs and embraces the immutability, the change detection strategy will kick in when:

  1. The Input reference changes;

  2. An event originated from the component or one of its children;

  3. Run change detection explicitly (componentRef.markForCheck());

  4. Use the async pipe in the view.

This has for effect to gain a lot on performance, Angular doesn’t do any guess or useless work. It makes your application embrace the immutability, via its components.

Last updated