Sub topic 1
What Zone.js does for Angular today
Before you remove Zone.js, you need to know which jobs it does in a zone-based app. This chapter covers those jobs: how Zone.js detects that something may have changed, how Angular turns that signal into a screen update, and what else Angular quietly gets from it. The later chapters on triggers, markForCheck, NgZone APIs and testing all replace one of these jobs.
Prerequisites
This chapter assumes you have:
- Built standalone components and templates in a recent Angular version (v18 or later).
- Basic TypeScript and asynchronous JavaScript: events,
setTimeout, Promises andasync/await. - Used the default change detection model, even without knowing how it works inside.
- Seen
signalandcomputed. You do not need them in this chapter.
The problem Zone.js solves
Angular renders a template by reading component fields. If a field changes, Angular has to find out and re-run the template. A plain class field gives no notification when you assign to it:
this.seconds++; // nothing tells Angular this happenedAngular's original answer was to avoid asking. Anything that could change state is asynchronous work: a click, a timer, a network response, a resolved Promise. Angular only needs to know when such work finishes, then it can check everything. Zone.js provides that notification.
How Zone.js works
Zone.js is a library that Angular's build loads as a polyfill. It monkey-patches the browser's asynchronous APIs, replacing the originals with wrappers. The patched set includes:
setTimeout,setIntervalandrequestAnimationFrameaddEventListeneron DOM eventsXMLHttpRequestandfetchPromise, includingthencallbacksqueueMicrotaskandMutationObserver
When your code calls a patched API, the wrapper records the current zone and later runs your callback inside that same zone. A zone is an execution context that survives across asynchronous gaps. It can carry hooks that run before and after each task.
Angular creates a zone called the Angular zone and wraps it in a class named NgZone. At bootstrap, Angular runs your application inside it. Every callback scheduled from your code then re-enters the Angular zone, and NgZone gets a hook when each task starts and ends.
NgZone exposes this as observable events. The two that matter here:
onMicrotaskEmptyemits when a task has finished and no microtasks remain queued.onStableemits right after, when the zone has fully drained.
From a browser event to a screen update
ApplicationRef subscribes to onMicrotaskEmpty. Each emission calls ApplicationRef.tick(), which runs change detection over the application. Angular has no change detection of its own to start the process. It borrows the signal "an async task just ended" from Zone.js.
Here is a component that works only because of this pipeline:
import { Component } from '@angular/core';
@Component({
selector: 'app-clock',
template: `<p>Seconds: {{ seconds }}</p>`,
})
export class Clock {
protected seconds = 0;
constructor() {
setInterval(() => {
this.seconds++;
}, 1000);
}
}seconds is an ordinary field and nothing marks it as changed. The view still updates every second, because setInterval is patched. Each tick ends a task in the Angular zone, onMicrotaskEmpty fires, and tick() re-renders. Remove Zone.js and this component stops updating. That is the main behavior change in the rest of the tutorial.
What the default strategy checks
Zone.js only says something may have changed. It does not say what. So with the default strategy (ChangeDetectionStrategy.Default), each tick() walks the whole component tree from the root. For every component it re-evaluates the template bindings and compares each value with the previous one. Changed values are written to the DOM.
This has useful properties and one cost:
- Developers rarely think about change detection, because any async path leads to a refresh.
- Mutating objects in place, or changing fields from anywhere, works.
- Work scales with the number of bindings in the whole app, on every event, even when nothing relevant changed.
Components with OnPush skip part of that work, as a later chapter explains. They are checked only when an input reference changes, an event fires from their template, or they are explicitly marked. A zone-based app still starts every tick() at the root.
Other jobs Zone.js does
Triggering change detection is the most visible job, but not the only one.
- Stability tracking. Because Zone.js sees every pending macrotask and microtask,
NgZonecan tell whether the app has outstanding work.ApplicationRef.isStableandwhenStable()build on this. Server-side rendering waits for stability before serializing HTML. Tests usefixture.whenStable()the same way. - Error capture. An uncaught error inside the Angular zone reaches
NgZone.onError, and Angular routes it toErrorHandler. This also covers errors thrown in a Promise callback. - Development checks. After each
tick()in dev mode, Angular runs a second pass,checkNoChanges. This pass findsExpressionChangedAfterItHasBeenCheckederrors. It does not depend on Zone.js, but zone-driven ticking makes it run constantly. - Hydration and router timing. Several framework features wait for
onStableto know when initial work is done.
Controlling the zone
NgZone lets you opt out of triggering. Code in runOutsideAngular does not cause change detection when its tasks finish. This is useful for high-frequency events like scroll or mousemove:
import { Component, ElementRef, NgZone, inject } from '@angular/core';
@Component({
selector: 'app-scroll-tracker',
template: `<p>Reached bottom: {{ atBottom }}</p>`,
})
export class ScrollTracker {
private readonly zone = inject(NgZone);
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
protected atBottom = false;
constructor() {
this.zone.runOutsideAngular(() => {
window.addEventListener('scroll', () => {
const reached =
window.innerHeight + window.scrollY >= document.body.scrollHeight;
if (reached !== this.atBottom) {
this.zone.run(() => {
this.atBottom = reached;
});
}
});
});
}
}The scroll listener runs outside the Angular zone, so most scroll events cost nothing. Only a real change re-enters with zone.run, which triggers one tick(). Zoneless mode makes this pattern unnecessary, because nothing triggers on scroll to begin with.
You can also tune triggering without leaving zones. provideZoneChangeDetection({ eventCoalescing: true }) merges several events in the same frame into one tick().
Costs and limits of Zone.js
These are the reasons the next chapter gives for going zoneless.
| Cost | Detail |
|---|---|
| Bundle size | Zone.js is an extra polyfill loaded before your app. |
| Startup and runtime overhead | Every patched API call goes through a wrapper. |
| Over-checking | Any async event refreshes the whole tree, relevant or not. |
| Native `async`/`await` | It cannot be patched. The CLI downlevels `async`/`await` to Promises so zones can follow it, which changes the emitted code. |
| Unpatched APIs | Some newer browser APIs are not patched, so changes made in their callbacks may not render. |
| Debugging | Stack traces include zone frames and are harder to read. |
| Interop | Libraries that run their own event loops can cause extra or missing refreshes. |
The async/await row is the one most often overlooked. Zone.js depends on Promise being a patchable object. Native async functions use the engine's internal promise machinery, which the patch cannot reach. Angular's build avoids the problem by compiling async functions to a form Zone.js can track.
Summary of the mechanism
- Zone.js patches browser async APIs and runs callbacks in the zone where they were scheduled.
- Angular runs your app in the Angular zone through
NgZone. - When a task ends and no microtasks remain,
onMicrotaskEmptyemits. ApplicationRefresponds withtick(), which checks the component tree from the root.- The same task tracking provides stability and error capture.
Zoneless Angular keeps steps 4 and 5 and replaces steps 1 to 3 with explicit notifications. Signals, template events and markForCheck tell Angular that a view needs checking.
Exercise
A zone-based component has the field count = 0 and the template {{ count }}. A fetch(...).then(r => r.json()).then(d => { this.count = d.total; }) callback assigns the field. Explain why the view updates, and name the Angular event that leads to the update.
Show answer
fetch and Promise.then are patched by Zone.js, so the callbacks run in the Angular zone. When the last callback ends and no microtasks remain, NgZone emits onMicrotaskEmpty. ApplicationRef subscribes to that event and calls tick(), which re-evaluates the template and writes the new count to the DOM. The field itself sends no notification.
Exercise
Why does running a scroll listener inside NgZone.runOutsideAngular improve performance in a zone-based app, and why does that technique matter less once the app is zoneless?
Show answer
In a zone-based app, every scroll event would end a task in the Angular zone and trigger a full tick(). Outside the zone, the listener does not trigger change detection, so only an explicit zone.run causes a refresh. In a zoneless app, nothing triggers change detection on a plain event listener, so scroll events never cause refreshes unless they update a signal or call markForCheck.