How does Angular 2 Change Detection Really Work ?

The Angular 2 change detection mechanism is much more transparent and easier to reason about than its equivalent in Angular 1. But there are still situations (like when doing performance optimizations) when we really need to know whats going on under hood. So let’s dig deeper into change detection by going over the following topics:

  • How is change detection implemented?
  • What does an Angular 2 change detector look like, can i see it ?
  • How does the default change detection mechanism work
  • turning on/off change detection, and triggering it manually
  • Avoiding change detection loops: Production vs Development mode
  • What does the OnPush change detection mode actually do?
  • Using Immutable.js to simplify the building of Angular 2 apps
  • Conclusions

How is change detection implemented?

Angular 2 can detect when component data changes, and then automatically re-render the view to reflect that change. But how can it do so after such a low-level event like the click of a button, that can happen anywhere on the page?

To understand how this works, we need to start by realizing that in Javascript the whole runtime is overridable by design. We can override functions in String or Number if we so want.

Overriding browser default mechanisms

What happens is that Angular 2 at startup time will patch several low-level browser APIs, such as for example addEventListener, which is the browser function used to register all browser events, including click handlers. Angular will replace addEventListener with a new version that does the equivalent of this:

Read the rest of the article here