Change detection Angular 2
Each component has its own detective to investigate changes

Change detection Angular 2

You may have read that in Angular2 you must apply the single responsibility principle per component.

For this reason, when you check the source code of a web page built with Angular2 you notice that it is constituted of multiple components, each is responsible on a certain part of the page.

This practice helps to easily read the code and maintain it over time as the application grows. Yet, it becomes tricky to track changes that affect certain models in order to reflect them in the DOM.

And this is where the change detection mechanism plays its role.

Although this mechanism works automatically so the developer doesn't have to be concerned about. Understanding it is crucial because it helps controlling the application’s performance, thusly enhance users’ experience.

For clarity reasons in the rest of the article “Angular2” will be replaced by “Angular”.

How change detection works?

At startup, Angular associates to each component a change detector.

Aucun texte alternatif pour cette image


When the change detector is triggered, what it does is that it loops on each property that is used in the DOM and compare its old value to the new one in order to decide if it has changed or not. Yes as simple as that 😄😄 !

But how change detection is triggered?

In other words, how does Angular know about changes in data? The answer, is that Angular assumes that data are modified whenever one of these three events occurs:

  • Events based on user interaction like click, mouseover, key-up...
  • HTTP requests.
  • setTimeout() and setInterval().

These events are defined as browser APIs. As their name indicates, they are APIs that are integrated in the web browser. Their role is to support complex operations and help accessing data.

How is angular notified about these events?

It gets notified thanks to the decorator pattern within JavaScript.

According to Wikipedia:

The decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class.

Long story short, when the application is bootstrapped, an instance of NGZone is created to load in its turn Zone.js. This latter is a library responsible on monkey patching browser's APIs.

What?!

Monkey patching is a term used to describe the effect of decorator pattern. Simply put, it means extending and modifying an API.

Zone.js monkey patches browser's APIs in order to add callbacks that will be invoked each time the API is called. In our case the callbacks are established to trigger change detection.

NGZone on the other hand, is a service that creates a zone named angular.

What is a zone?

According to Angular official site:

A zone is an execution context that persists across async tasks. You can think of it as thread-local storage for JavaScript VMs.


It is important here to not confuse the comparison of async operations to threads. JavaScript is not a multithreading language. This analogy, however, came in order to define async operations as code fragments that run independently of the main code. On the other hand, thread-local storage is about specifying local memory space where to store its thread's variables independently. That being said, zone is a space in which async operation can run and it enables us to detect when this latter starts and finishes. This way Zone.js is able to alter APIs and add change detection callbacks to them.

So last but not least, angular zone is unique per application and change detection can be triggered only for async operations that were defined inside it.

Pros of Angular's change detection mechanism:

The factor that every component has its own change detector, is powerful for several reasons:

  • It is possible to control launching change detector for one component or another.
  • It is virtual machine (VM) friendly. Instead of a global dynamic change detector that has to discover about each component's properties a side. Having a custom change detector that looks like any code written by a human, makes it easy on the VM to transform it into native code.
  • It is fast. As it is created from the start and it is fitted to component's properties that are only displayed in the DOM, this allows it to perform thousands of simple checks within few milliseconds.

Change detection always performs from top to bottom and it has a unidirectional dataflow, means that always the controller updates his view (never the other way round). This makes it predictable and simple to reason about.

Is it possible to optimize change detection?

Change detection is already conceived to be very fast. However, by the time user interfaces become more complex. Moreover, Angular performs change detection on the whole DOM tree. So to avoid lags and latency it is necessary to optimize triggering this mechanism.

OnPush strategy:

In addition to the default change detection strategy explained previously there is another one called OnPush. This strategy is applied on components individually. It tells Angular to check a component and its children only when one of their inputs is changed. It is very helpful because it prevents checking a whole subtree in case none of the async events previously mentioned are invoking views' changes.

RunOutsideAngular:

Whenever there is an async event that doesn't trigger view's changes, it is possible to run this event outside of angular zone by using runOutsideAngular() method. This way we avoid running unnecessary checks and so enhance application's performance.

Detaching the change detector:

This method allows to disable checks for a component by calling the detach method provided in change detector. The good thing about it is it's reversible at runtime which means change detection can be re-enabled whenever a method "reattach" is used.

Raja Aissi

Sr. UX Designer@InfoCert

4y

Thanks for sharing, that was so interesting :)

To view or add a comment, sign in

More articles by Henda Farhani

  • Microservices centralized configuration by Spring Cloud and state changes' broadcast via Spring Cloud Bus and RabbitMQ.

    This article explains: How to create a centralized configuration for microservices' instances. How to notify those…

  • Docker for beginners

    Let's start by defining Docker It is a runtime environment designed to create, build and manage applications in…

    4 Comments
  • Micro-services architecture

    What is micro-services ? According to Wikipedia, Micro-services is a software development technique that structures an…

    6 Comments
  • Redux

    Redux is an open source JavaScript library for managing application state. It was created in June 2015 and it was…

    2 Comments

Insights from the community

Others also viewed

Explore topics