Reduce Change Detection Cycles with Event Coalescing in Angular

Netanel Basal
Netanel Basal
Published in
2 min readDec 10, 2019

--

In this article, I want to talk about a new feature introduced in the latest Angular release (v9) — ngZoneEventCoalescing. First, we need to understand the problem it is meant to solve. Let’s say we have the following component’s template:

When we click on the button element, it first runs the handlers on it, then on its parent, then it continues upwards through the DOM tree. This is what’s known as event bubbling. (🦊)

As you probably know, Angular uses ZoneJS to intercept events that occurred in the application and run a change detection cycle automatically. If you want to know how it works under the hood, check out my previous articles.

Returning to our code snippet, when we click on the button, we also invoke the parent element’s handler, causing two change detection cycles to run. Let’s see this in action:

As we can see, Angular calls the tick method twice, one for each event handler.

Starting from Angular v9, we have the option to instruct Angular to coalesce these events. We do this by setting the new ngZoneEventCoalescing property to true in the bootstrapModule method:

Now if we run the same process, we can see that Angular runs only a single change detection cycle:

If we take a look at the source code, we’ll see that it works by employing a simple check of whether we want to coalesce the events:

If that’s the case, Angular defers the change detection cycle using requestAnimationFrame.

🚀 In Case You Missed It

Here are a few of my open source projects:

  • Akita: State Management Tailored-Made for JS Applications
  • Spectator: A Powerful Tool to Simplify Your Angular Tests
  • Transloco: The Internationalization library Angular
  • Forms Manger: The Foundation for Proper Form Management in Angular
  • Cashew: A flexible and straightforward library that caches HTTP requests

Follow me on Medium or Twitter to read more about Angular, Akita and JS!

--

--

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.