Change detection

Angular can feel pretty magical when you start using it.

For instance, how does it know when inputs change? How does it re-render elements? We won't be able to delve very deeply into how things work under the hood, but we can at least give you a rough idea.

When Angular is loaded, it patches many browser APIs in order to know when some things happen. Most of these patches are handled by the zone.js (https://github.com/angular/zone.js) library that Angular uses (and which might also get standardized at some point in the future). Thanks to those patches, Angular knows when buttons are clicked on, when event listeners are triggered, when (most) asynchronous operations are completed, and more.

When Angular notices that something relevant has happened, it triggers a change detection cycle. The goal of that process is indeed to detect changes in order to re-render only necessary elements.

Each Angular component has an implicit change detector that will verify whether anything has changed in that component. This means that there is a parallel change detector tree right next to the component tree of your application.

By querying that change detector tree, Angular can precisely determine what has changed (if anything) in your application and can then re-render only the changed parts. The change detection cycle goes from the top of the component tree (that is, your root/app component) to the bottom and can fully check your application in one pass.

By default, Angular checks whether any values of template expressions differ from their previous state. This method is usually called dirty-checking and the verification is performed for all components.

Angular is really fast and can perform thousands of checks in a few milliseconds. Of course, as applications grow larger, things take longer. It is possible to optimize the process, for example, by using immutable data structures. Immutable objects provide the stability guarantee that values won't change unless the corresponding variable is reassigned. While using immutable data structures, we can simply tell Angular to skip some checks by setting the changeDetection property of specific components to ChangeDetectionStrategy.OnPush. You can learn more about that as follows: https://netbasal.com/a-comprehensive-guide-to-angular-onpush-change-detection-strategy-5bac493074a4.

Let's introduce Angular services.