Sub topic 14
Running high-frequency events outside the Angular zone
This chapter assumes you know Angular components and services, can read a basic Performance panel trace, and understand how Zone.js triggers change detection (covered in earlier chapters). You will learn how to spot events that fire too often, move their listeners outside the Angular zone, and re-enter the zone only when the view must update.
Why high-frequency events are costly
Zone.js patches browser APIs such as addEventListener, setTimeout, and requestAnimationFrame. When a patched callback finishes inside the Angular zone, NgZone signals that the zone is stable again. Angular then runs change detection from the root of the application.
For a click, that is what you want. For scroll, mousemove, resize, or pointermove, it is not. These events can fire dozens of times per second. Each one schedules a full change detection pass, even if your handler changes nothing that the template displays.
In a trace, this shows up as a repeating pattern in the Main track:
- An event task, such as
Event: scroll. - Your handler, usually very short.
- A longer block of Angular work below it, with frames such as
ApplicationRef.tickand component template functions.
If the Angular block is much larger than your handler, the framework work is the cost, and the event is a candidate for running outside the zone.
Confirming the problem in a trace
Do not move listeners on suspicion. Measure first, as in the earlier chapters.
- Record a trace in the Performance panel on a production-like build.
- Perform the interaction, such as scrolling for a few seconds.
- Look for many short tasks, each followed by Angular frames.
- Select a few of them and compare the time spent in your handler with the time spent in
ApplicationRef.tick. - Optionally open Angular DevTools and record a profile. If components change detect once per scroll event but their output never changes, the passes are wasted.
The Summary tab for a selected range also helps. A large share of scripting time spent in framework code during a gesture that changes nothing on screen is a strong signal.
Moving a listener outside the zone
NgZone.runOutsideAngular() runs a function in the parent zone, where Angular is not watching. Any listener registered inside that function stays outside the Angular zone, even when it fires later.
import { Component, NgZone, OnDestroy, OnInit, inject } from '@angular/core';
@Component({
selector: 'app-scroll-tracker',
template: `<ng-content />`,
})
export class ScrollTrackerComponent implements OnInit, OnDestroy {
private zone = inject(NgZone);
private onScroll = () => {
// Lightweight work that does not need to update the view.
};
ngOnInit() {
this.zone.runOutsideAngular(() => {
window.addEventListener('scroll', this.onScroll, { passive: true });
});
}
ngOnDestroy() {
window.removeEventListener('scroll', this.onScroll);
}
}Three details matter here:
- Registration is what counts. The listener is attached inside
runOutsideAngular, so every later invocation also runs outside the zone. - Cleanup is manual. Angular does not remove a listener you attached with
window.addEventListener. WithoutngOnDestroy, each created component leaks a listener and its closure. The Memory panel can confirm such leaks. passive: truetells the browser the handler never callspreventDefault(), so scrolling does not wait for your code.
Re-entering the zone when the view must change
Sometimes the handler should update the UI only under a condition, for example showing a "back to top" button after the user scrolls past 400 pixels. Do the cheap check outside the zone and re-enter only when the state changes.
import { Component, NgZone, OnDestroy, OnInit, inject, signal } from '@angular/core';
@Component({
selector: 'app-back-to-top',
template: `@if (visible()) { <button type="button">Back to top</button> }`,
})
export class BackToTopComponent implements OnInit, OnDestroy {
private zone = inject(NgZone);
visible = signal(false);
private onScroll = () => {
const shouldShow = window.scrollY > 400;
if (shouldShow !== this.visible()) {
this.zone.run(() => this.visible.set(shouldShow));
}
};
ngOnInit() {
this.zone.runOutsideAngular(() => {
window.addEventListener('scroll', this.onScroll, { passive: true });
});
}
ngOnDestroy() {
window.removeEventListener('scroll', this.onScroll);
}
}The handler fires many times, but zone.run() executes only when the button's visibility flips. That turns hundreds of change detection passes into two.
Edge cases and common mistakes
- Registering in the wrong place. If you call
addEventListenerfirst and wrap only the handler body inrunOutsideAngular, the event still enters the zone. Wrap the registration. - Forgetting to re-enter. Changing a plain field outside the zone leaves the screen stale in a zone-based app. Signals notify Angular on their own in recent versions, but do not rely on that when the code also uses non-signal state. Use
zone.run()when in doubt. - Third-party libraries. Chart and map libraries often attach many listeners. Initialize them inside
runOutsideAngular, then callzone.run()from their callbacks only when you need Angular to react. - Timers.
setIntervalandrequestAnimationFrameloops behave the same way. A 60 fps animation loop inside the zone triggers 60 passes a second. - Template listeners.
(scroll)="..."in a template always runs inside the zone. For frequent events, attach the listener in code instead. - Tests. In unit tests with
NgZonemocked or in zoneless setups,runOutsideAngularsimply runs the callback. Behavior is the same, but the benefit disappears because no zone is watching.
Zoneless Angular removes this problem differently: change detection is scheduled only by signals, markForCheck, and similar notifications, so a bare event listener does not trigger it. If your app uses zoneless mode, this technique is unnecessary.
Checking that it helped
Record the same interaction again with the same throttling and the same build. Compare:
| Measure | Before | After |
|---|---|---|
| Number of `ApplicationRef.tick` calls during a 5 second scroll | Many | Few or none |
| Scripting time in the Summary tab | Higher | Lower |
| Longest task in the Main track | Longer | Shorter |
Use a fixed gesture, such as scrolling the same distance at a steady pace, so the runs are comparable. The next chapters cover the Memory and Network panels, and the last chapter formalizes this before-and-after method.
Exercise
A component attaches a mousemove listener with window.addEventListener inside ngOnInit. A trace shows a change detection pass after every event, yet the handler only stores coordinates in a private field. Which two changes would you make, and what would you check in a new trace?
Show answer
Register the listener inside this.zone.runOutsideAngular(...), and remove it in ngOnDestroy with the same function reference. Record the same mouse movement again on the same build and throttling. The ApplicationRef.tick frames after each mousemove should be gone, and scripting time for the gesture should drop.
Exercise
Why does the back-to-top example call zone.run() only when shouldShow differs from visible()?
Show answer
The scroll handler runs outside the zone, so it does not trigger change detection by itself. Calling zone.run() on every event would bring back a pass per event. Calling it only when the value flips triggers change detection only when the view actually needs to change.