Sub topic 13
Zoneless change detection: what changes without Zone.js
This chapter assumes you know the Default and OnPush strategies, how markForCheck marks a component and its ancestors dirty, and how signals are read in templates. It also assumes you know what Zone.js does in the standard setup: it patches browser APIs so Angular learns that "something may have changed". Here you will see what replaces that mechanism when you remove Zone.js, which of your code keeps working, and which code silently stops updating the screen.
What Zone.js was doing for you
In a zone-based app, Zone.js patches setTimeout, promises, DOM event listeners, XMLHttpRequest and similar APIs. When a patched callback finishes, NgZone emits onMicrotaskEmpty, and ApplicationRef runs a change detection pass over the tree. Angular never learns what changed or which component changed. It only learns that some asynchronous work ended, so it checks everything that is not skipped by OnPush.
This design has three costs:
- Every finished callback triggers a pass, even if no state changed (a
mousemovehandler that does nothing, for example). - Zone.js adds to the bundle size and to start-up work, and it patches every asynchronous API on the page.
- Native
async/awaitcannot be patched, so the build must downlevel it to promises.
Zoneless change detection removes the guesswork. Angular runs a pass only when something explicitly tells it that a view needs one.
Enabling zoneless mode
Add the zoneless provider at bootstrap:
import { provideZonelessChangeDetection } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { App } from './app/app';
bootstrapApplication(App, {
providers: [provideZonelessChangeDetection()],
});Then remove zone.js from the polyfills array of the build target in angular.json, and from the test target if you use the Angular test builder. If you leave the polyfill in place, Zone.js still patches the browser APIs and you keep its overhead, although Angular will not use it to schedule checks.
In Angular 21 and later, new projects are generated zoneless by default. An existing app that still depends on Zone.js must opt into it with provideZoneChangeDetection(). Check your version's documentation for the exact defaults.
What schedules a pass without Zone.js
A scheduler inside Angular replaces the zone trigger. It listens for a fixed set of notifications. When one arrives, it schedules a pass for shortly afterward. It races requestAnimationFrame against setTimeout and uses whichever fires first, so several notifications in the same moment are batched into one pass.
The notifications are:
- A signal read in a template changes its value.
ChangeDetectorRef.markForCheck()is called. Theasyncpipe calls it for you when a new value arrives.ComponentRef.setInput()is used, for example by the router and by dynamic component creation.- A listener bound in a template or on the host runs, such as
(click)="..."or@HostListener. - A view that was marked dirty is attached, or a view is removed.
The following changes do not schedule a pass:
- Assigning to a plain field in a
setTimeout,setIntervalor promise callback. - Mutating an object that an OnPush child receives as an input.
- A
WebSocketmessage handler that writes to plain fields.
Under Zone.js, a Default component would still have updated in these cases, because the zone triggered a pass and Default components are always checked. Without the zone, nothing is notified, so the screen stays stale.
The practical rule: write OnPush-compatible code
Components that follow the OnPush rules from the earlier chapters already work in zoneless apps. An OnPush component updates only through the notifications listed above, and those are the same ones the zoneless scheduler listens for. Zoneless adds one more constraint: even Default components no longer get a free pass, so every component needs a real notification when its state changes.
The ticker from the markForCheck chapter works unchanged in zoneless mode, because markForCheck is a scheduler notification. A signal version is shorter and does not need ChangeDetectorRef:
import { ChangeDetectionStrategy, Component, OnDestroy, signal } from '@angular/core';
@Component({
selector: 'app-ticker',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Seconds: {{ count() }}</p>`,
})
export class Ticker implements OnDestroy {
count = signal(0);
private id = setInterval(() => this.count.update((c) => c + 1), 1000);
ngOnDestroy() {
clearInterval(this.id);
}
}Writing to count from a timer callback is enough. The template reads count(), so Angular knows this component depends on it and schedules a pass when the value changes.
Here is the broken counterpart. It looks fine in a zone-based Default component, and it never updates in a zoneless app:
import { Component, OnDestroy } from '@angular/core';
@Component({
selector: 'app-stale-ticker',
template: `<p>Seconds: {{ count }}</p>`,
})
export class StaleTicker implements OnDestroy {
count = 0;
private id = setInterval(() => this.count++, 1000);
ngOnDestroy() {
clearInterval(this.id);
}
}The field changes every second, but no signal, markForCheck, input or template event announces it, so the view keeps showing 0.
Comparing the two models
| Question | Zone.js | Zoneless |
|---|---|---|
| What starts a pass? | Any patched async callback finishing | Explicit notifications only |
| Does Angular know which component changed? | No, it checks the tree minus OnPush skips | Yes, for signals and `markForCheck`; dirty views are tracked |
| Plain field written in `setTimeout` | View updates in Default components | View does not update |
| Event handler in a template | Triggers a pass | Triggers a pass (listener notification) |
| Extra work from unrelated events | Common, for example `mousemove` | None unless a notification fires |
| Bundle and start-up | Includes Zone.js | No Zone.js |
APIs that stop being useful
Several APIs are tied to the zone and behave differently or do nothing in a zoneless app:
NgZone.onMicrotaskEmpty,onStableandonUnstablenever emit, so code that waits for them hangs. UseafterNextRender,afterEveryRenderorApplicationRef.whenStable()instead.NgZone.run()andrunOutsideAngular()still execute your callback, but they no longer control change detection. The earlier technique of movingmousemovehandlers outside the zone is unnecessary here, because a handler that sets no signal and calls nomarkForCheckcosts nothing. Keep the calls only if a library still needs them.- A library that relied on Zone.js to refresh the view after its callbacks may stop updating your UI. Check whether it supports zoneless, or wrap its callbacks so they write to a signal.
Errors and tests
ExpressionChangedAfterItHasBeenChecked still exists. In development mode Angular still runs a second verification pass after each tick and compares binding values. A value that changes during a pass, for example a signal written in a lifecycle hook after the parent view was checked, still raises the error. Zoneless mode does not make that bug go away. It does make it less common, because signal-based state encourages updates outside the render pass.
Tests change too. Without a zone, nothing runs a pass after an await in a test. Call fixture.detectChanges() after a state change, or use await fixture.whenStable() to let the scheduler finish a scheduled pass. To test zoneless behavior, add provideZonelessChangeDetection() to the test module's providers. A test that passes with Zone.js can fail without it because it relied on automatic passes.
Migrating step by step
- Switch every component to OnPush. This shows missing notifications while Zone.js is still present, so you can fix them without losing the safety net.
- Move template state to signals, or keep observables behind the
asyncpipe. - Replace
onStableandonMicrotaskEmptyusage withafterNextRender,afterEveryRenderorwhenStable(). - Add
provideZonelessChangeDetection()and removezone.jsfrom the polyfills. - Run the app and the tests, and interact with every feature that uses timers, sockets or third-party widgets.
Exercise
A zoneless app has an OnPush component with message = 'Loading' and a template {{ message }}. A promise callback sets this.message = 'Done'. The screen still shows "Loading". Give two changes that fix it, and say which one you would choose.
Show answer
Make message a signal (message = signal('Loading')), read it as {{ message() }}, and write it with this.message.set('Done'). Alternatively, inject ChangeDetectorRef and call markForCheck() after assigning the plain field. Both send a notification to the scheduler, which was missing before. The signal is the better choice. Angular tracks which component reads it, you cannot forget the notification, and the code works the same with or without Zone.js.
Exercise
Why does a mousemove listener registered with window.addEventListener cost nothing in a zoneless app, even without runOutsideAngular?
Show answer
The listener is not bound in a template or on the host, and it does not write a signal or call markForCheck. So it sends no notification to the scheduler and no pass runs. Under Zone.js, the patched addEventListener would trigger a pass after every event.