Sub topic 3
NgZone APIs in a Zoneless Angular Application
Assume you know standalone components, signals, Promises, and Angular’s default change detection. In zoneless mode, Angular no longer treats every task inside NgZone as a reason to check the view.
NgZone APIs that change meaning
NgZone.run() and NgZone.runOutsideAngular() still control the execution context, but entering the Angular zone does not itself schedule change detection. Use them for compatibility with libraries that inspect the current zone, not as a view-update mechanism.
Likewise, onStable and onUnstable no longer describe the complete application lifecycle when stability depends on Zone.js task tracking. Use signals for state updates and PendingTasks for work that must delay application stability.
import { ChangeDetectorRef, Component, NgZone, inject } from '@angular/core';
@Component({
selector: 'app-status',
template: `<p>{{ status }}</p>`,
})
export class Status {
private readonly zone = inject(NgZone);
private readonly cdr = inject(ChangeDetectorRef);
protected status = 'Waiting';
start() {
this.zone.runOutsideAngular(() => {
setTimeout(() => {
this.status = 'Ready';
this.cdr.markForCheck();
}, 500);
});
}
}Pending work and errors
PendingTasks tells Angular that asynchronous work is still active. This matters for server rendering and tests that await stability.
import { Injectable, PendingTasks, inject } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class DataLoader {
private readonly pending = inject(PendingTasks);
load(url: string) {
return this.pending.run(async () => {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
});
}
}Zone.js previously helped surface some asynchronous errors through Angular. Without it, catch Promise and timer failures explicitly, then pass them to Angular’s ErrorHandler when appropriate.
Testing, migration, and compatibility
Configure provideZonelessChangeDetection() in tests and await fixture.whenStable() after actions that schedule work.
Migrate incrementally:
- Enable zoneless mode in a branch.
- Replace mutable template state with signals.
- Add
markForCheck()or theasyncpipe for remaining observable state. - Remove
zone.jsfrom build and test polyfills. - Test navigation, rendering, and error paths.
Check third-party libraries that mutate fields from timers or callbacks. A library that only invokes a callback is usually usable, but your callback must update a signal or notify Angular.
Exercise
Why does NgZone.run() not fix every missed update in a zoneless application?
Show answer
It changes the execution context, but it does not notify Angular that a view needs checking. Update a signal, use the async pipe, or call markForCheck().