Sub topic 11
Where OnPush fits in zoneless Angular
What this chapter assumes
You should already know the earlier chapters of this tutorial. That means how Zone.js tells Angular that something may have changed, how default change detection checks the whole tree, and what marks an OnPush component for checking. You should also be comfortable with markForCheck, the async pipe, and reading signals in templates.
This chapter covers what changes when Zone.js is removed, and why the habits you built for OnPush carry over almost unchanged.
What zoneless means
In a zone-based app, Zone.js patches browser APIs such as setTimeout, promises, and DOM event listeners. When any patched task finishes, NgZone tells Angular, and Angular runs a change detection pass over the application. Angular does not know what changed. It only knows that something might have.
A zoneless app has no patching and no such blanket signal. Angular instead runs change detection only when something notifies it that a view may be out of date. The notification sources are explicit and few.
Zoneless support was introduced as experimental in Angular 18 under the name provideExperimentalZonelessChangeDetection(). Later versions renamed it provideZonelessChangeDetection() and moved it toward stable, and recent versions make zoneless the default for new projects. The API name and the default depend on your Angular version, so check the documentation for the version you use.
The benefits are practical:
- Smaller bundles, because
zone.jsis no longer shipped. - Fewer change detection passes, because unrelated async work (a timer in a third-party library, for example) no longer triggers a check.
- Readable stack traces and no patched native APIs.
- Native
async/awaitworks without being downleveled, which Zone.js required.
What notifies Angular without Zone.js
In zoneless mode, Angular schedules a change detection pass when one of these happens:
- A signal that is read in a template changes.
ChangeDetectorRef.markForCheck()is called. The async pipe calls it for you.ComponentRef.setInput()sets an input. Template bindings to inputs use the same mechanism.- A template or host listener (for example
(click)) runs. - A view that was marked dirty is attached, or a view is removed.
Anything else does not notify Angular. Assigning to a plain field inside a setTimeout, a promise callback, or a manual subscribe callback changes the data but schedules nothing.
Compare this list with the OnPush triggers you learned earlier. They are almost the same list. OnPush already forced you to tell Angular when a component's state changed. Zoneless extends that rule to the whole application.
Enabling zoneless change detection
Enabling zoneless takes two steps. First, add the provider when you bootstrap the application.
import { bootstrapApplication } from '@angular/platform-browser';
import { provideZonelessChangeDetection } from '@angular/core';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, {
providers: [provideZonelessChangeDetection()],
}).catch((err) => console.error(err));Second, remove Zone.js from the build. In an Angular CLI project, delete zone.js from the polyfills array of the build target in angular.json, and delete zone.js/testing from the test target.
{
"polyfills": []
}If you leave Zone.js loaded and also provide the zoneless provider, the app still works, but you keep the bundle cost and the patched APIs. Remove Zone.js once your app is ready.
Apps that keep Zone.js can still benefit from the same scheduler. Signals and markForCheck also schedule a pass in zone-based apps, so code written for zoneless runs fine in either mode. That makes a gradual migration possible: first make components notify Angular correctly, then switch the provider.
OnPush is not required, but it is the right preparation
Zoneless does not force you to use ChangeDetectionStrategy.OnPush. A component with the default strategy still works. When a pass runs, Angular checks every default component that is reachable in the tree, as it always did.
The catch is that a pass only runs if something notified Angular. A default component that updates a plain field from a timer will not get its view refreshed, because no pass was scheduled. This is the same bug OnPush produces with unnotified async updates, but now it affects default components too.
The Angular documentation therefore describes OnPush as the recommended, compatible strategy for zoneless apps. A component written correctly for OnPush meets these conditions:
- Inputs are replaced rather than mutated.
- Async data reaches the template through the async pipe, signals, or an explicit
markForCheck. - No code relies on "something ran, so Angular will check me."
Such a component is already zoneless-compatible. Components that rely on Zone.js catching every event are the ones that break.
The table summarizes how the common sources behave.
| Source of change | Zone-based, Default | Zone-based, OnPush | Zoneless |
|---|---|---|---|
| Template `(click)` handler | Checked | Checked | Checked |
| Plain field set in `setTimeout` | Checked | Stale | Stale |
| Signal read in template changes | Checked | Checked | Checked |
| `async` pipe emits | Checked | Checked | Checked |
| Mutated input object | Checked | Stale | Stale |
| Manual `subscribe`, plain field, no `markForCheck` | Checked | Stale | Stale |
The OnPush column and the zoneless column are identical. That is the main point of this chapter. An app that is correct under OnPush behaves the same way without Zone.js.
A bug that appears when you remove Zone.js
This component works in a default zone-based app and breaks in a zoneless one.
import { Component } from '@angular/core';
@Component({
selector: 'app-status',
template: `<p>{{ message }}</p>`,
})
export class StatusComponent {
message = 'Loading...';
constructor() {
setTimeout(() => {
this.message = 'Ready';
}, 1000);
}
}With Zone.js, the patched setTimeout finishes and Angular runs a pass, so the view shows "Ready". Without it, nothing notifies Angular. The paragraph stays at "Loading..." even though message has changed.
The fix is the same one you would apply for OnPush. Move the state into a signal and read it in the template.
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
@Component({
selector: 'app-status',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ message() }}</p>`,
})
export class StatusComponent {
message = signal('Loading...');
constructor() {
setTimeout(() => {
this.message.set('Ready');
}, 1000);
}
}The set call marks the view dirty and schedules a pass. Adding OnPush here costs nothing and documents the intent. A markForCheck call after a plain field assignment would also work, but signals are the clearer option for local state.
Signals are the natural fit
Signals suit zoneless Angular because they carry their own notification. When a template reads count(), Angular records that the view depends on that signal. When the signal changes, Angular marks only that view dirty and schedules a pass.
This is why the earlier chapter on signals and OnPush said the update works without markForCheck. In zoneless mode, signals are not an optional extra. They are the primary way to hold state that changes outside a template event.
RxJS code still works. Use the async pipe in the template, or convert an Observable with toSignal from @angular/core/rxjs-interop.
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-ticker',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Ticks: {{ ticks() }}</p>`,
})
export class TickerComponent {
ticks = toSignal(interval(1000), { initialValue: 0 });
}toSignal subscribes when the component is created and unsubscribes when it is destroyed. Each emission sets the signal, which notifies Angular.
Other code that depended on NgZone
Zone.js did more than trigger change detection, and some code relied on those extras. Watch for these cases when you migrate.
NgZone.onStableandNgZone.onMicrotaskEmptydo not emit in a zoneless app. Code that waits for them to run after rendering must change. UseafterNextRenderorafterEveryRenderfor post-render work.NgZone.run()andrunOutsideAngular()still exist but have no effect on change detection. Leaving them in is harmless, but they no longer optimize anything.- Third-party libraries that assumed Zone.js would trigger a check after their callbacks may leave views stale. If a library calls your code from its own callbacks, notify Angular yourself in that code.
- Application stability, which
ApplicationRef.whenStable()reports, is tracked through the scheduler and pending tasks instead of zone tasks. Server-side rendering waits on the same signal, so work that must finish before serialization should usePendingTasksrather than a bare promise.
Finding unnotified updates
The failure mode is quiet. No error appears, and the view just shows old data. Two techniques help.
First, switch to zoneless in development early, even before you remove Zone.js from production. Any stale view that appears is a missing notification.
Second, use Angular's development-mode checks. ExpressionChangedAfterItHasBeenChecked errors still appear when a binding's value changes during a pass. Recent Angular versions also offer a stricter check, enabled through provideCheckNoChangesConfig, that can detect state changed without a notification. Look in the documentation for your version to confirm its name and options before relying on it.
Testing in zoneless mode
Tests that use fixture.detectChanges() after each step still work with OnPush components. In a zoneless test setup, the recommended approach is to let the scheduler do its job and wait for it with await fixture.whenStable(). This catches missing notifications that a forced detectChanges() would hide, because detectChanges() renders regardless of whether anything scheduled a pass.
Provide the zoneless provider in the test module.
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { StatusComponent } from './status.component';
describe('StatusComponent (zoneless)', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideZonelessChangeDetection()],
});
});
it('shows Ready after the timer fires', async () => {
vi.useFakeTimers();
const fixture = TestBed.createComponent(StatusComponent);
await fixture.whenStable();
expect(fixture.nativeElement.textContent).toContain('Loading...');
await vi.advanceTimersByTimeAsync(1000);
await fixture.whenStable();
expect(fixture.nativeElement.textContent).toContain('Ready');
vi.useRealTimers();
});
});This example uses Vitest's vi for fake timers. With Jasmine or Jest, substitute that framework's fake-timer API. The key line is the second whenStable(). If the component still used a plain field, the text would remain "Loading..." and the test would fail, which is the behavior you want it to reveal.
Set inputs with fixture.componentRef.setInput() rather than assigning to the component instance. Direct assignment bypasses the notification, just as it does with OnPush.
Decision criteria
Choose zoneless when you are starting a new application, or when an existing application already uses OnPush, signals, and the async pipe throughout. Defer it when the application depends on libraries that assume Zone.js and have no zoneless support, or when large parts of the code mutate state in callbacks and have no tests to expose missing notifications.
A migration order that works in practice:
- Switch components to
OnPush, fixing mutation and unnotified updates as they surface. - Move component state that changes asynchronously into signals.
- Replace
NgZone.onStable-style waits with render hooks. - Add
provideZonelessChangeDetection()in a development build and run the tests. - Remove
zone.jsfrom the polyfills.
Exercise
A default-strategy component in a zoneless app has items: string[] = []. A fetch(...).then(...) callback in its constructor assigns this.items = result, and the template uses @for (item of items; track item). The list never appears. Why, and what is the smallest fix?
Show answer
Nothing notifies Angular after the promise callback sets a plain field, so no change detection pass is scheduled. Without Zone.js, the patched promise no longer triggers one. The smallest fix is to make items a signal (items = signal<string[]>([])), call this.items.set(result) in the callback, and read items() in the template. Calling markForCheck() after the assignment would also work.
Exercise
Why does the chapter say that a component written correctly for OnPush is already close to zoneless-compatible?
Show answer
OnPush already requires the developer to ensure that Angular is notified of every state change that does not come from an input replacement or a template event. The notification sources are the async pipe, signals, markForCheck, and setInput. These are the same sources that zoneless Angular uses to schedule change detection, so code that follows OnPush rules does not depend on Zone.js to catch its updates.
Exercise
In a zoneless test, why is await fixture.whenStable() preferred over calling fixture.detectChanges() after each step?
Show answer
detectChanges() forces a render whether or not anything scheduled a pass, so it can hide a missing notification. whenStable() waits for the pass that the scheduler actually runs, so the test fails when the component never notified Angular. That makes the test reflect what happens in the browser.