Angular Change Detection

Angular Change Detection

A brief introduction

How to explain someone how change detection works in Angular?

Components in Angular are structured as a tree. A lot of abstractization on it

By default, Angular detects if the reference of something that is bound to HTML changes

Every time it changes, it runs the change detection for all the tree nodes. It will start from AppRef which is the root node.

This is quite inefficient because it checks the whole tree, even if many of the components would not need to rerender

If you change from default change detection to OnPush change detection, Angular will trigger change detection for the specific branch only if:

  • @Input values references changed

  • Event functions triggered (click), (scroll), timeout, setInterval and AJAX Http Requests

  • Async pipe used

For the event-bound method, this is possible because Angular overrides the addEventListener function which is browser native to something improved, that calls the markForCheck method

The caveat with the async pipe is that manually under the hood it triggers the change detection for the node and its parents. It calls markForCheck()

Usually, when you use OnPush change detection you use the following two methods

  • markForCheck() - This will trigger change detection for the current node and its parents

  • detectChanges() - This will trigger change detection for the current node ONLY

As good practice, don't use OnPush when immutability is not possible because it checks the reference, not the insides of the object.