
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:
@Component({
template: `
<div (click)="parent()">
<button (click)="child()">Submit</button>
</div>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {
parent() {
console.log('parent');
}
child() {
console.log('child');
}
}
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:
platformBrowserDynamic()
.bootstrapModule(AppModule, { ngZoneEventCoalescing: true })
.catch(err => console.error(err));
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:
const delayChangeDetectionForEventsDelegate =
() => delayChangeDetectionForEvents(zone)
const maybeDelayChangeDetection = !!zone.shouldCoalesceEventChangeDetection &&
zone.nativeRequestAnimationFrame && delayChangeDetectionForEventsDelegate;
onInvokeTask: (..) => {
try {
onEnter(zone);
return delegate.invokeTask(target, task, applyThis, applyArgs);
} finally {
if (maybeDelayChangeDetection && task.type === 'eventTask') { <=======
maybeDelayChangeDetection();
}
onLeave(zone);
}
},
sds
Comments
Post a Comment