Sub topic 13
Migrating an existing application step by step
This chapter assumes you know standalone components, signal and computed, and the basic idea of OnPush. It also assumes you have read the earlier chapters on what schedules change detection without zones. Here you apply that knowledge to an app that already exists and works.
Plan the migration as stages
Do not remove Zone.js first. A zone-based app can behave correctly by accident, because Zone.js triggers a check after almost every async event. Removing it exposes every place where the app depended on that accident. Move in stages, and keep the app working after each one.
Stages 2 and 3 work in a zone-based app too. You can ship them one component at a time, which keeps each change small and easy to review.
Stage 1: Audit the code
Search the codebase for the things that behave differently without zones.
| Search for | Why it matters |
|---|---|
| `NgZone`, `ngZone.run`, `runOutsideAngular` | In zoneless mode these still run your callback, but they no longer affect change detection. |
| `onStable`, `onMicrotaskEmpty`, `isStable` | These observables do not emit usefully without zones. Code that waits on them can hang or run at the wrong time. |
| `ChangeDetectionStrategy.Default` or no `changeDetection` setting | The component relies on being checked after every event. |
| `setTimeout`, `setInterval`, `Promise.then`, `fetch` that assign to plain fields | Zone.js used to schedule a check after these. Nothing does now. |
| `provideZoneChangeDetection`, `zone.js` imports | Configuration to remove later. |
Write down the components that mutate plain fields from async callbacks. These are the most likely to break.
Stage 2: Move components to OnPush
OnPush components are checked only when an input changes, an event handler in their template fires, a signal they read changes, or markForCheck() is called. These are the same triggers a zoneless app uses, so an OnPush component behaves almost the same in both modes.
Add changeDetection: ChangeDetectionStrategy.OnPush to a component, then run the app and click through it. If something stops updating, the component was relying on the default strategy. Fix it before you continue. Start at the leaves of the component tree, then work up toward the root.
Stage 3: Convert state to signals
A plain field that is assigned in an async callback is the typical failure. Here is a component that works under the default strategy in a zone-based app:
import { Component } from '@angular/core';
@Component({
selector: 'app-profile',
template: `<p>{{ name }}</p>`,
})
export class Profile {
protected name = 'Loading...';
constructor() {
setTimeout(() => {
this.name = 'Ada';
}, 500);
}
}Zone.js patches setTimeout, so a check runs after the callback. Without zones, the text stays at "Loading...". The preferred fix is a signal:
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
@Component({
selector: 'app-profile',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ name() }}</p>`,
})
export class Profile {
protected readonly name = signal('Loading...');
constructor() {
setTimeout(() => {
this.name.set('Ada');
}, 500);
}
}Reading name() in the template registers a dependency. Calling set notifies Angular, which schedules a check.
Some state is hard to convert quickly, for example a field in a large class that other code mutates directly. In that case, keep the field and call markForCheck() after each change:
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);
}
}Treat markForCheck() as a bridge. It works, but it is easy to forget on one code path. Convert to signals when you next touch the component.
For values that come from RxJS streams, use the async pipe or toSignal(). Both notify Angular when a new value arrives. A manual subscribe that assigns a plain field is the other common source of missed updates, so search for those as well.
Stage 4: Enable zoneless and keep zone.js loaded
Now add the provider. Leave zone.js in the polyfills for this stage.
import { bootstrapApplication } from '@angular/platform-browser';
import { provideZonelessChangeDetection } from '@angular/core';
import { App } from './app/app';
bootstrapApplication(App, {
providers: [provideZonelessChangeDetection()],
});If the app used provideZoneChangeDetection({ eventCoalescing: true }), remove it. The two providers are alternatives, so use only one.
Keeping Zone.js loaded gives you a safety margin. The app no longer relies on Zone.js to schedule change detection. Third-party libraries or your own code that depend on its patched APIs still find them. If something breaks at this stage, the cause is a missing notification in your code, not a missing polyfill. That makes the bug easier to locate.
Click through every screen with the app running in development mode. Watch for these symptoms:
- A value that updates only after you click somewhere else.
- A spinner that never disappears.
- A list that stays empty until a second event arrives.
Each symptom is a state change that did not notify Angular. In Angular 20 and later you can also add provideCheckNoChangesConfig({ exhaustive: true }) to the providers during development. It makes the dev-mode check report bindings that changed without a notification. Remove it again if the extra checks slow down your dev builds.
Stage 5: Remove zone.js
Once the app is clean, delete Zone.js from the build. In angular.json, remove "zone.js" from the polyfills list in both the build and test targets, so each is empty:
"polyfills": []Also delete any import 'zone.js' or import 'zone.js/testing' line from polyfills.ts or main.ts, and uninstall the package if nothing else needs it. Check the bundle size afterward. The saving is the Zone.js runtime plus its patches.
Replace the leftover NgZone code you found in the audit:
- Remove
runOutsideAngularcalls that only existed to avoid triggering checks. They are harmless but now misleading. - Rewrite code that waits on
onStableoronMicrotaskEmpty. UseafterNextRender,afterEveryRender, orApplicationRef.whenStable()instead, depending on what you were waiting for. - Remove
NgZone.isInAngularZone()assertions, because they have no meaning in this mode.
Stage 6: Tests, pending work and errors
Tests
Tests need the same provider, and they must wait for Angular to run its scheduled check. Without Zone.js there is no automatic fixture.detectChanges() after every event, so await fixture.whenStable() is how you wait.
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');
});
});Avoid fakeAsync in these tests, because it depends on Zone.js. Use Jasmine's clock or Vitest's fake timers instead, and then await stability.
A test that passes only because it calls fixture.detectChanges() can hide a real bug. In zoneless mode, prefer whenStable(), so the test exercises the same scheduling path as the running app.
Pending work and server rendering
With zones, Angular knew the app was stable when no tasks were in flight. Without zones, it only knows about work you tell it about. Server rendering waits for stability before it serializes the page, so untracked async work can be cut off. Wrap such work in PendingTasks:
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();
});
}
}Angular's own HttpClient and router already register their work. Wrap your own fetch calls, timers and third-party async APIs.
Errors
Zone.js used to catch uncaught errors from async callbacks and send them to ErrorHandler. In a zoneless app, add provideBrowserGlobalErrorListeners() to the providers so uncaught errors and unhandled promise rejections reach ErrorHandler. New projects include it by default. Older projects need it added by hand.
Order of work in a large app
For a large app, do not convert everything in one pull request. A practical sequence:
- Add
OnPushto shared and leaf components first, in small pull requests. - Convert state to signals feature by feature, starting with the features that have good tests.
- Enable zoneless in a branch or behind a build configuration while you fix what breaks.
- Remove Zone.js only after the end-to-end suite passes with it enabled and zoneless active.
Common mistakes
- Removing Zone.js and enabling zoneless in the same change, which makes the cause of a failure unclear.
- Assigning plain fields inside
subscribecallbacks and not callingmarkForCheck(). - Leaving
fakeAsynctests in place after removingzone.js/testing. - Forgetting
PendingTasksfor custom async work and then seeing incomplete server-rendered pages.
Exercise
A component has protected items: string[] = [] and loads data with this.api.get().subscribe(list => this.items = list). It uses ChangeDetectionStrategy.OnPush. After you enable zoneless mode, the list never appears. Give two ways to fix it and say which you would prefer.
Show answer
The assignment inside subscribe changes a plain field, so nothing notifies Angular. Fix 1: make items a signal (items = signal<string[]>([])), call this.items.set(list) in the callback, and read items() in the template. Fix 2: keep the field and call this.cdr.markForCheck() after the assignment, or expose the stream with toSignal() or the async pipe. Prefer the signal-based fix, because notification is built into the state and cannot be forgotten on one code path. Use markForCheck() only as a temporary bridge.