Sub topic 9
NgZone APIs that no longer do what you expect
This chapter assumes you can enable zoneless mode with provideZonelessChangeDetection(), and that you know how signals and OnPush components schedule updates. It covers what happens to code that calls NgZone, and how to replace each pattern.
Why NgZone still exists in a zoneless app
NgZone is an injectable service. Components, libraries and your own services inject it, so removing it would break every one of them at startup. In zoneless mode Angular keeps the token and supplies a no-op implementation behind it. The class has the same methods, but they no longer watch anything.
The result is code that compiles, runs without errors, and silently stops doing its job. This chapter is about finding those places.
What each member does without zones
The zone-based NgZone wraps Zone.js. It tracks microtasks and macrotasks and emits events when the zone becomes busy or empty. The no-op version only forwards calls.
| Member | Zone-based behavior | Zoneless behavior |
|---|---|---|
| `run(fn)` | Runs `fn` inside the Angular zone, then change detection follows | Calls `fn` directly. No change detection is triggered |
| `runGuarded(fn)` | Like `run`, with errors routed to `onError` | Calls `fn` directly |
| `runOutsideAngular(fn)` | Runs `fn` where timers and events do not trigger change detection | Calls `fn` directly. Nothing was going to trigger it anyway |
| `onMicrotaskEmpty` | Emits when no microtasks remain, which drives change detection | Never emits |
| `onStable` | Emits after the zone finishes its turn | Never emits |
| `onUnstable` | Emits when the zone starts a turn | Never emits |
| `onError` | Emits uncaught errors from the zone | Never emits |
| `isStable`, `hasPendingMacrotasks`, `hasPendingMicrotasks` | Reflect tracked work | Fixed values, `true` for `isStable` and `false` for the pending flags |
The key point is the difference between the two groups. run and runOutsideAngular still execute your function, so they are harmless. The observables and flags no longer carry information, so code that depends on them is wrong.
Mermaid requires the diagram fence format given below, so here is the diagram in the correct form.
The silent failure: run() no longer refreshes the view
The most common bug is code written like this, usually around a third-party callback:
this.zone.run(() => {
this.items = newItems;
});In a zone-based app, leaving run ended a zone turn, and Angular checked the views. In zoneless mode, run just calls the function. A plain field assignment does not notify Angular, so the template keeps showing the old data.
The fix is the same as for any non-signal state. Hold the value in a signal:
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
@Component({
selector: 'app-items',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ul>
@for (item of items(); track item) {
<li>{{ item }}</li>
}
</ul>
`,
})
export class Items {
protected readonly items = signal<string[]>([]);
// Called by a library outside Angular's control.
onLibraryData(newItems: string[]) {
this.items.set(newItems);
}
}Alternatively, keep the field and call ChangeDetectorRef.markForCheck() after changing it, as the previous chapter showed. Do not wrap the call in run() and hope.
runOutsideAngular becomes optional, but keep it in shared code
In a zone-based app, runOutsideAngular stopped high-frequency events such as mousemove or requestAnimationFrame loops from triggering change detection on every tick. In a zoneless app, a raw addEventListener callback does not schedule change detection at all. Only a signal write, a template listener, markForCheck and the other notifications from earlier chapters do.
Two situations call for leaving the wrapper in place:
- Hybrid apps. During migration you may still use
provideZoneChangeDetection()with Zone.js loaded. There the wrapper does real work. - Shared libraries. If the same code ships to zone-based and zoneless apps,
runOutsideAngularis cheap and correct in both.
This service works in either mode:
import { Injectable, NgZone, inject, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class PageVisibility {
private readonly zone = inject(NgZone);
readonly hidden = signal(document.hidden);
constructor() {
this.zone.runOutsideAngular(() => {
document.addEventListener('visibilitychange', () => {
this.hidden.set(document.hidden);
});
});
}
}The signal write tells Angular a view may need updating. That is why the service needs no run() call to push the value back in. In an app you own and have fully migrated, you can drop the NgZone injection and call addEventListener directly.
Replacing onStable and onMicrotaskEmpty
Code that subscribed to onStable usually wanted one of two things: run after the DOM updated, or run when the app has finished its work. Zoneless Angular has a separate tool for each.
After the DOM updated
Use the render hooks afterNextRender (once) and afterEveryRender (every cycle). They run after Angular has written to the DOM, and they work in both zone-based and zoneless apps. Call them in an injection context, such as a constructor or field initializer.
import {
afterNextRender,
ChangeDetectionStrategy,
Component,
ElementRef,
signal,
viewChild,
} from '@angular/core';
@Component({
selector: 'app-measured-box',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div #box>Content</div>
<p>Box width: {{ width() }}px</p>
`,
})
export class MeasuredBox {
private readonly box = viewChild.required<ElementRef<HTMLElement>>('box');
protected readonly width = signal(0);
constructor() {
afterNextRender(() => {
this.width.set(this.box().nativeElement.offsetWidth);
});
}
}The old pattern was zone.onStable.pipe(take(1)).subscribe(...). In a zoneless app that subscription never fires, so the width would stay at 0 with no error. Writing to the signal inside the hook schedules a further pass, so the new value renders.
After the app has finished its work
Use ApplicationRef.whenStable(), which returns a promise, or the ApplicationRef.isStable observable. Stability in zoneless mode depends on Angular's own tracking: pending change detection, router navigation, HttpClient requests, and anything you register with PendingTasks.
import { ApplicationRef, Injectable, inject } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class AfterStable {
private readonly appRef = inject(ApplicationRef);
async run(task: () => void): Promise<void> {
await this.appRef.whenStable();
task();
}
}Your own asynchronous work is invisible to this check unless you register it. A setTimeout or a bare fetch does not hold stability open. Wrap such work in PendingTasks.run(), which a later chapter covers.
Static helpers and the global Zone
NgZone.isInAngularZone() and NgZone.assertInAngularZone() are static methods. They read the global Zone object, not the injected service. Once you remove zone.js from the polyfills, that global does not exist. Treat any call to these methods as a bug to remove, not as a no-op. They usually appear in guard clauses such as "if not in the zone, re-enter with run". Delete the guard and use signals for the state change.
The same goes for any code that touches Zone.current or Zone.root directly. This includes some older logging, tracing and test utilities. Search for the identifier Zone as well as NgZone.
Finding the usages
A grep over the source is enough to build the list. Search for these terms:
onStable,onMicrotaskEmpty,onUnstable,onErrorisStable,hasPendingMacrotasks,hasPendingMicrotasksisInAngularZone,assertInAngularZoneZone.current,Zone.root,fakeAsyncandwaitForAsyncin tests
For each hit, apply the decision in the diagram. In practice, most run and runOutsideAngular hits can stay until you finish migrating. Most event and flag hits need real replacements, because they fail silently.
Common mistakes
- Keeping
run()as the update mechanism. The code runs, nothing refreshes. Use a signal ormarkForCheck. - Waiting on
onStablefor a measurement. The subscriber never fires. UseafterNextRender. - Calling
afterNextRenderoutside an injection context. Angular throws. Pass aninjectoroption if you must call it later. - Assuming
whenStable()covers a raw timer. It does not. Register the work withPendingTasks. - Removing
runOutsideAngularfrom a library that also supports zone-based apps. Those apps then check on every event. Keep the wrapper.
Exercise
A service calls this.zone.onStable.pipe(take(1)).subscribe(() => this.scrollToTop()) to scroll after the first render. The app has switched to zoneless mode and the scroll never happens. Why, and what is the replacement?
Show answer
In zoneless mode NgZone is a no-op implementation, so onStable never emits and the subscription never fires. Replace it with afterNextRender(() => this.scrollToTop()), called in an injection context such as the service or component constructor. The hook runs once after Angular has rendered, and it works with or without Zone.js.
Exercise
A component updates this.total = value inside this.zone.run(() => ...) from a callback of a charting library. After going zoneless the displayed total is stale. Give two ways to fix it.
Show answer
First, store the total in a signal (total = signal(0)) and call this.total.set(value), reading total() in the template. Second, keep the plain field and call ChangeDetectorRef.markForCheck() after assigning it. Wrapping the assignment in zone.run() fixes nothing, because the no-op run only calls the function.