Sub topic 6
Enabling zoneless mode and removing zone.js
This chapter shows how to switch a standalone Angular application to zoneless change detection and remove Zone.js from the build. It assumes you can build standalone components, you know the default change detection model, and you have used signal and computed. It covers the provider, the build configuration, server rendering and the errors you are most likely to meet.
What the switch changes
In a zone-based app, Zone.js patches browser APIs such as setTimeout, addEventListener and Promise. After any patched task finishes, NgZone emits an event and Angular runs change detection over the whole component tree.
Zoneless mode removes that automatic trigger. Angular runs change detection only when something tells it to. The framework has an internal scheduler for this. Signal reads in templates, template event listeners, the async pipe and markForCheck() all notify that scheduler, and the scheduler then runs a check. The next chapter covers these triggers in detail.
Two separate steps are involved, and they are easy to confuse:
- Providing zoneless change detection tells Angular to stop listening to
NgZone. - Removing
zone.jsfrom the build stops the library being loaded and patching browser APIs.
You can do step 1 without step 2. Doing both gives the bundle-size and performance benefits.
Step 1: Add the provider
Add provideZonelessChangeDetection() to the application providers in main.ts.
import { bootstrapApplication } from '@angular/platform-browser';
import { provideZonelessChangeDetection } from '@angular/core';
import { App } from './app/app';
bootstrapApplication(App, {
providers: [provideZonelessChangeDetection()],
});The provider replaces the default NgZone-based scheduling with the zoneless scheduler. It does not remove zone.js by itself.
Note that in some Angular versions the provider is exported under an experimental name, provideExperimentalZonelessChangeDetection. Check the version you use. In current releases the stable name shown above is the one to use.
Apps that bootstrap with NgModule
If the app still uses NgModule, add the same provider to the providers array of the root module. The call looks like this:
import { NgModule, provideZonelessChangeDetection } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { App } from './app';
@NgModule({
declarations: [App],
imports: [BrowserModule],
providers: [provideZonelessChangeDetection()],
bootstrap: [App],
})
export class AppModule {}Step 2: Remove zone.js from the build
Open angular.json and find the polyfills option under both the build and test targets. Remove the "zone.js" entry. If that was the only entry, the option becomes an empty list:
"polyfills": []Do this for each project and each target that lists it. A typical file has build and test entries, and sometimes server for server-side rendering.
Then check for other places that load the library:
src/polyfills.ts, in older projects, may containimport 'zone.js';. Remove that line.src/polyfills.tsmay also importzone.js/testing. Remove it too.package.jsonlistszone.jsas a dependency. You can uninstall it once nothing imports it.
npm uninstall zone.jsDo not uninstall the package until a build succeeds without it. A leftover import gives a "module not found" error, which points you straight at the file to fix.
Confirming the app is actually zoneless
A common mistake is to add the provider and leave zone.js in the polyfills. The app then runs with Zone.js loaded but with Angular ignoring it. That can hide bugs, because third-party code still triggers patched tasks that no longer trigger checks. Verify the result in three ways:
- Open the browser console and type
Zone. In a zoneless build it isundefined. - Compare the bundle. The
polyfillschunk should shrink or disappear. - Look at the build output for the polyfills entry. After removal it lists no Zone.js code.
Making components work
With the scheduler changed, every component must tell Angular when its view needs updating. The safest pattern is OnPush plus signals. A signal read in the template registers the component as a dependency, and writing to the signal schedules a check.
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
@Component({
selector: 'app-counter',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<button (click)="increment()">Clicked {{ count() }} times</button>`,
})
export class Counter {
protected readonly count = signal(0);
increment() {
this.count.update((c) => c + 1);
}
}The click handler runs because Angular's template listener fires. The update call changes the signal, which marks the component dirty and schedules change detection. No Zone.js is involved.
Components that use the default strategy can still work, but only when a notification arrives. Using OnPush makes the dependency on notifications explicit, so missed updates show up early.
Plain fields need explicit notification
A plain field changed inside a timer gives Angular no signal. Nothing marks the view dirty, so the screen stays stale.
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, inject } from '@angular/core';
@Component({
selector: 'app-legacy-timer',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Seconds: {{ seconds }}</p>`,
})
export class LegacyTimer {
private readonly cdr = inject(ChangeDetectorRef);
protected seconds = 0;
constructor() {
setInterval(() => {
this.seconds++;
this.cdr.markForCheck();
}, 1000);
}
}markForCheck() flags the component and its ancestors, and in zoneless mode it also schedules a check. Converting seconds to a signal is usually cleaner, and later chapters cover that choice.
Flow of an update
The diagram shows the path from an event to a rendered view in a zoneless app.
Server rendering
Zoneless mode works with server-side rendering (SSR). The server needs to know when the page is ready to serialize. In a zone-based app, Zone.js tracks pending tasks to decide this. Without it, Angular relies on its own record of pending work. Work started with Angular APIs such as HttpClient is tracked for you. Custom asynchronous work is not, so wrap it:
import { Injectable, inject, PendingTasks } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class DataLoader {
private readonly pendingTasks = inject(PendingTasks);
load(url: string) {
return this.pendingTasks.run(async () => {
const response = await fetch(url);
return response.json();
});
}
}If you skip this, the server may serialize the page before the data arrives and send incomplete HTML. A later chapter covers PendingTasks in more depth.
In an SSR project, remove zone.js from the server polyfills too, and make sure the server bootstrap uses the same providers as the browser bootstrap.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| View does not update after a timer or callback | Plain field changed with no notification | Use a signal or call `markForCheck()` |
| `Zone` is still defined in the console | `zone.js` still in `polyfills` or imported in a file | Remove it from `angular.json` and source files |
| Build fails with "Cannot find module 'zone.js'" | An import remains after uninstalling | Search the project for `zone.js` and remove it |
| Tests fail with timing errors | Tests assume zone-driven change detection | Enable zoneless in `TestBed` and await stability |
| SSR output misses async data | Custom async work not tracked | Wrap it in `PendingTasks.run()` |
Search the whole project for leftovers with one command:
grep -rn "zone.js" --include="*.ts" --include="*.json" . --exclude-dir=node_modulesKeeping the test setup consistent
The test configuration must match the app. Remove zone.js and zone.js/testing from the test polyfills, then enable zoneless in TestBed:
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { Counter } from './counter';
describe('Counter', () => {
it('updates the view after a click', async () => {
TestBed.configureTestingModule({
providers: [provideZonelessChangeDetection()],
});
const fixture = TestBed.createComponent(Counter);
await fixture.whenStable();
fixture.nativeElement.querySelector('button').click();
await fixture.whenStable();
expect(fixture.nativeElement.textContent).toContain('Clicked 1 times');
});
});Use await fixture.whenStable() instead of calling fixture.detectChanges() repeatedly. A zoneless fixture runs checks through the same scheduler as the app, so awaiting stability reflects real behavior. A later chapter covers testing in full.
Summary of the procedure
- Add
provideZonelessChangeDetection()to the root providers. - Remove
zone.jsfrompolyfillsinangular.jsonfor build, test and server targets. - Delete
zone.jsimports from source files and uninstall the package. - Check that
Zoneis undefined in the browser console. - Update tests to use zoneless providers and
await fixture.whenStable(). - Wrap custom asynchronous work in
PendingTasks.run()for server rendering.
Exercise
You added provideZonelessChangeDetection() to a project and left "zone.js" in the build polyfills. Typing Zone in the browser console shows an object. What does that tell you, and what should you do to finish the switch?
Show answer
Zone.js is still loaded and patching browser APIs, so the app is not fully zoneless even though Angular ignores NgZone for scheduling. Remove "zone.js" from polyfills in the build (and test, and server if present) targets of angular.json, delete any import 'zone.js' lines in source files, rebuild, and confirm Zone is undefined in the console.
Exercise
A zoneless component shows {{ total }} where total is a plain number field. A setTimeout callback increases total, but the screen never changes. Give two ways to fix it.
Show answer
Convert total to a signal, read it as total() in the template, and update it with set or update, which schedules a check. Alternatively, inject ChangeDetectorRef and call markForCheck() after changing the field in the callback. The signal approach is preferred.