Skip to content

Change Detection and Zoneless Angular

Almost every hard Angular bug that is not a logic bug is a change-detection bug. A value updates but the screen does not. A screen updates but only after you click somewhere else. A page burns CPU while idle. A test passes locally and fails in CI. An ExpressionChangedAfterItHasBeenCheckedError appears in a component nobody touched.

All of those come from the same root question: how does Angular know that something changed? For most of Angular’s history the answer was “ZoneJS guesses.” Modern Angular’s answer is “you tell it.” That change reframes the entire topic, and it is the single most common area where developers carry a mental model that is several years out of date.

Get these straight before anything else, because the words are overloaded.

  • Change detection (CD) — Angular walking the component tree, re-evaluating template expressions, and updating the DOM where the result differs.
  • A change-detection cycle or pass — one traversal. Angular batches; it does not run a pass per state mutation.
  • Dirty — a view flagged as needing to be re-checked on the next pass.
  • Scheduling — Angular deciding that a pass should happen soon. Scheduling is separate from running.
  • ZoneJS (zone.js) — a library that monkey-patches browser async APIs (setTimeout, addEventListener, Promise, XHR, …) so that Angular gets a callback whenever an async task finishes. It is a change signal, not a change detector.
  • NgZone — Angular’s wrapper around a ZoneJS zone. NgZone.runOutsideAngular() executes code in a zone Angular ignores.
  • Zoneless — running Angular without zone.js loaded, relying on explicit notifications instead.

Think of change detection as three separate mechanisms that people constantly conflate:

  1. Notification — “something might have changed.” Historically ZoneJS; now explicit API calls and signal writes.
  2. Marking — which views are dirty. Angular marks a view dirty and walks up marking ancestors, so the path from root to the dirty view is checkable.
  3. Refresh — the traversal itself, which decides per component whether to re-evaluate its template.

The classic bugs map cleanly onto these:

Symptom Broken mechanism
UI never updates Notification never fired
UI updates on unrelated click Notification missing; a later unrelated one flushed the state
Idle CPU burn Notification fires far too often
ExpressionChangedAfterItHasBeenCheckedError Refresh read a value that a previous phase of the same pass changed

Diagnose in that order. Reaching for detectChanges() skips diagnosis and papers over a notification bug.

import { Component, signal } from '@angular/core';
@Component({
selector: 'order-counter',
template: `
<p>Orders in cart: {{ count() }}</p>
<button (click)="add()">Add</button>
`,
})
export class OrderCounter {
readonly count = signal(0);
add(): void {
this.count.update((n) => n + 1);
}
}

Two notifications happen here and it is worth being precise about which does what:

  • The (click) binding is an Angular-bound listener, so handling it notifies Angular on its own.
  • count.set/count.update marks every view that read that signal in its template as dirty.

The second is what makes this component correct in any configuration. If add() were called from a setTimeout, a WebSocket callback, or a promise resolution, the signal write would still schedule a refresh. That is the property you want: correctness that does not depend on where the code ran.

For years, ChangeDetectionStrategy.Default meant “check this component on every pass, always,” and OnPush was the opt-in optimisation. As of Angular 22 that is inverted: components are OnPush unless you say otherwise, and the old Default value has been renamed:

export enum ChangeDetectionStrategy {
OnPush = 0, // the default
Eager = 1,
/** @deprecated Use `Eager` instead. */
Default = 1,
}

Default still compiles — it is the same numeric value as Eager — but it is deprecated, and new code should write Eager when it genuinely needs eager checking.

An OnPush component subtree is re-checked only when:

  • Its root component receives a new input as the result of a template binding. Angular compares previous and current values with ==.
  • Angular handles an event — an event binding, an output binding, or @HostListener — in the subtree root or any of its children, whether or not those children are OnPush.
  • A signal read in its template is written.
  • Something calls ChangeDetectorRef.markForCheck() on it. The AsyncPipe does this for you.
  • ComponentRef.setInput() is called on it.
  • A view previously marked dirty by one of the above is attached.

That list is the whole contract. Commit it to memory; every “why doesn’t my view update” question is answered by finding which item you expected to apply and did not.

Mutating an object without changing the reference. Angular compares inputs by reference (==). This does nothing:

// In the parent
addLine(): void {
this.order.lines.push(newLine); // same array reference
}

The child’s order input is == to what it was, so nothing is marked. Replace the reference (this.order = { ...this.order, lines: [...this.order.lines, newLine] }) or, better, hold the state in a signal the child reads.

Setting an input imperatively from TypeScript. Reaching a child via viewChild() and assigning to its input bypasses the template-binding path entirely, so no marking happens. Use ComponentRef.setInput() when you are creating components programmatically, or restructure so the value flows through a binding.

Async work outside any binding. A setInterval that assigns to a plain field notifies nothing under zoneless. Under ZoneJS it happened to work, which is exactly why so much code silently depended on ZoneJS.

Zoneless is the default from Angular v21 onwards. New applications ship without zone.js, and there is nothing to enable. If you are on v20, opt in at bootstrap:

bootstrapApplication(OrdersPortal, {
providers: [provideZonelessChangeDetection()],
});

If you are on v21+ and change detection behaves like the old model, the usual cause is a leftover provideZoneChangeDetection() in a providers array overriding the default. Search for it first.

The official rationale is worth stating precisely rather than paraphrasing as “it’s faster”:

  • Performance. ZoneJS treats DOM events and async tasks as evidence that state might have changed. It has no insight into whether it actually did, so it triggers synchronisation far more often than necessary.
  • Core Web Vitals. ZoneJS costs both payload size and startup time.
  • Debugging. Stack traces are harder to read with ZoneJS in them, and “this broke because it ran outside the Angular zone” is a genuinely difficult class of bug.
  • Ecosystem compatibility. ZoneJS patches browser APIs, and it does not automatically have patches for every new one. Some APIs — notably native async/await — cannot be patched effectively and had to be downlevelled to work with it.

That last point is the strategic one. ZoneJS was a permanent maintenance tax that grew as the web platform grew.

Going zoneless is not just a provider. Until you remove the polyfill you still ship the bytes:

  1. Remove zone.js from the polyfills array in angular.json — in both the build and test targets. Projects with an explicit polyfills.ts should delete import 'zone.js'; and import 'zone.js/testing';.
  2. npm uninstall zone.js.

Do step 1 before step 2, and run the build in between. Removing the package while a polyfill entry still references it produces a resolution error that reads like a dependency problem rather than a configuration one.

OrdersPortal shows a live order feed over a WebSocket, plus a filter, plus a total. It is the shape where change-detection mistakes actually hurt.

import { Component, computed, inject, signal, DestroyRef } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { OrderApiClient } from './order-api-client';
interface Order {
readonly id: string;
readonly customer: string;
readonly total: number;
readonly status: 'pending' | 'shipped' | 'cancelled';
}
@Component({
selector: 'orders-portal',
template: `
<input [value]="filter()" (input)="filter.set($any($event.target).value)" />
<p>{{ visible().length }} of {{ orders().length }} orders — {{ visibleTotal() | currency }}</p>
@for (order of visible(); track order.id) {
<order-row [order]="order" />
} @empty {
<p>No orders match.</p>
}
`,
})
export class OrdersPortal {
private readonly api = inject(OrderApiClient);
readonly orders = signal<readonly Order[]>([]);
readonly filter = signal('');
readonly visible = computed(() => {
const term = this.filter().toLowerCase();
return this.orders().filter((o) => o.customer.toLowerCase().includes(term));
});
readonly visibleTotal = computed(() =>
this.visible().reduce((sum, o) => sum + o.total, 0),
);
constructor() {
this.api
.orderStream()
.pipe(takeUntilDestroyed())
.subscribe((order) => {
this.orders.update((current) => [order, ...current.slice(0, 199)]);
});
}
}

Walk through what makes this correct without ZoneJS:

  • The WebSocket callback runs in whatever context the socket library chose. Angular does not know or care, because orders.update() marks the view dirty.
  • visible() and visibleTotal() are computed, so they recalculate only when orders or filter actually change, and only when something reads them. Two template reads of visibleTotal() would still be one calculation.
  • orders.update returns a new array. Signals compare with Object.is by default, so mutating the existing array in place would notify nothing.
  • track order.id lets Angular reuse DOM nodes rather than tearing down and rebuilding rows. Without a stable track expression, every socket message rebuilds the whole list — the most common cause of “the list flickers and my input loses focus.”
  • takeUntilDestroyed() unsubscribes on destroy. A leaked subscription that keeps writing to a signal on a destroyed component is a slow, invisible performance leak.

The slice(0, 199) bound is deliberate. An unbounded live feed is a memory leak with extra steps, and rendering thousands of rows makes every subsequent pass more expensive whatever your CD strategy is.

Some internals that explain otherwise-confusing behaviour.

The dirty flag lives on the view, not the component. When you call markForCheck(), Angular sets a flag on the component’s LView and then walks up the parent chain setting a “has dirty descendant” marker. The next pass can therefore skip whole subtrees without walking them: at each node it checks whether this view is dirty or contains a dirty descendant, and if neither, it stops.

The compiler only emits the strategy when it is non-default. Angular’s component definition computes onPush: changeDetection !== ChangeDetectionStrategy.Eager, and the compiler omits the changeDetection field entirely when it resolves to OnPush. So “OnPush is the default” is implemented as an absence in the compiled output, not a value.

Signals mark views, not expressions. A signal keeps a set of consumers. A template that reads a signal registers the whole view as a consumer. Writing the signal marks that view dirty — Angular does not track which specific interpolation depends on it. This is why extracting a frequently-changing signal into a small child component is a real optimisation: it shrinks the dirty view.

computed is lazy and memoised. It does not recompute on write; it recomputes on the next read after a dependency changed. A computed nobody reads costs nothing. This is the mechanical reason computed is preferable to a method call in a template — {{ recalculate() }} runs on every single check.

Refresh happens in a loop with a bound. After a pass, if any views were marked dirty during the pass, Angular runs again. Development builds additionally re-check bindings and throw ExpressionChangedAfterItHasBeenCheckedError if a value differs between the two reads. That error is a development-only guard against a rendering pass whose output depends on how many times it ran.

Under ZoneJS, a charting or mapping library that installs mousemove handlers or a requestAnimationFrame loop triggers a full application change-detection pass on every tick. In Angular DevTools’ profiler this shows up unmistakably: dense consecutive bars sourced from setTimeout, setInterval, requestAnimationFrame, or an event handler, on a page where nothing is visibly happening.

The fix is to initialise such libraries outside the zone:

private readonly ngZone = inject(NgZone);
ngOnInit(): void {
this.ngZone.runOutsideAngular(() => {
this.chart = createChart(this.host.nativeElement, this.config);
});
}

Two things people get wrong here. First, listeners registered inside runOutsideAngular also fire outside the zone — so if you need to update component state from one, write to a signal (which notifies regardless of zone) or re-enter with ngZone.run(). Second, and counter-intuitively: NgZone.run and runOutsideAngular remain compatible with zoneless applications and should not be stripped out during a migration. Angular explicitly warns that removing them can cause performance regressions in libraries still used by Zone-based applications. They become no-ops where there is no zone, which is harmless.

These must be removed, not merely reviewed:

  • NgZone.onMicrotaskEmpty, NgZone.onUnstable, NgZone.onStable — these observables never emit in a zoneless application.
  • NgZone.isStable — always true, so any code branching on it takes the same path forever.

The usual intent behind them was “wait until Angular has finished rendering.” Replace with the right tool:

Old intent Replacement
Wait for one render to complete afterNextRender()
React across several render rounds afterEveryRender()
Wait for specific DOM state MutationObserver / ResizeObserver
Wait for a measurement before painting afterEveryRender({ earlyRead, write })

The last row matters for layout thrashing. afterEveryRender accepts phased callbacks (earlyRead, write, mixedReadWrite) so all DOM reads happen before all DOM writes, instead of interleaving and forcing repeated synchronous layout.

Silent failure is the risk here. Code subscribed to onStable does not error under zoneless — it simply never runs. Grep for these four names as a hard gate in any migration.

SSR needs to know when the application is “stable” enough to serialise. With ZoneJS that came for free. Without it, you must tell Angular about async work that should block serialisation:

private readonly pendingTasks = inject(PendingTasks);
async loadReport(): Promise<void> {
await this.pendingTasks.run(async () => {
const report = await this.api.fetchReport();
this.report.set(report);
});
}

For work that does not fit a single callback, add and remove manually — and use finally, because a task never removed means SSR waits forever:

const cleanup = this.pendingTasks.add();
try {
await doWorkThatMustBeRendered();
} finally {
cleanup();
}

For observables, pendingUntilEvent() from @angular/core/rxjs-interop keeps the application unstable until the source emits, completes, errors, or is unsubscribed.

Angular uses this service internally too — in-flight HttpClient requests and ongoing router navigations already register pending tasks, so you do not need to wrap those yourself.

A genuine sharp edge worth calling out separately: reactive forms model updates do not schedule change detection. setValue, patchValue, FormArray.push and friends update form state and emit on the form’s observables, but they do not notify Angular that a view needs refreshing.

If a template depends on reactive-forms state, connect it explicitly — subscribe and call ChangeDetectorRef.markForCheck(), pipe through the AsyncPipe, or mirror the value into a signal the template reads. This one surprises people because forms feel like framework state.

Calling detectChanges() to make something appear. This forces a synchronous pass rather than fixing the missing notification. It hides the bug, runs more work than necessary, and breaks the moment the component is used somewhere the author did not anticipate.

ChangeDetectorRef.detach() as an optimisation. Detaching a view stops Angular refreshing it at all, and now correctness depends on you remembering every place that needs reattach() or a manual detectChanges(). It is occasionally right for a deliberately hand-driven visualisation; it is almost never right for application UI.

Method calls in templates. {{ formatTotal(order) }} or *ngIf="hasPermission()" re-executes on every check of that view. Use computed, a pure pipe, or a precomputed field.

Object or array literals in template bindings. [config]="{ dense: true }" creates a new object every check, so a child’s == input comparison is always false and the child is refreshed forever. Hoist it to a field.

Doing work in ngDoCheck / ngAfterViewChecked. These run on every check of the component. Layout reads or heavy computation here multiply by the number of passes and are a classic cause of a UI that gets slower the longer the page is open.

Mutating state inside a lifecycle hook that runs during the pass. This is what produces ExpressionChangedAfterItHasBeenCheckedError. Move the write earlier (to the constructor or an event handler) or, if it truly must happen after render, into afterNextRender().

Symptom Likely cause First check
Value updates in TS, never in DOM Nothing notified Angular Is the state a signal? Was it mutated in place?
Updates only after clicking elsewhere Missing notification; a later event flushed it Which async source wrote the value?
ExpressionChangedAfterItHasBeenCheckedError Value changed after the view was checked Which lifecycle hook writes to a bound value?
Idle page burns CPU Zone pollution from a library, or an interval DevTools profiler — look at the source of each pass
List flickers, input loses focus Missing or unstable track Is track a stable identity, not $index over a re-sorted list?
Works in dev, breaks in prod Relied on a dev-only extra check Build with production config locally and re-test
Test passes, production stale Test forced detectChanges() Convert to await fixture.whenStable()

Two tools do the heavy lifting.

Angular DevTools profiler. Record, interact, then read the timeline. Each bar is a pass and is labelled with what triggered it. A wall of bars from setTimeout on an idle page is zone pollution. One very tall bar is a slow computation — click it to see the per-component breakdown of template evaluation versus lifecycle hooks.

provideCheckNoChangesConfig. Angular can periodically verify that no binding was updated without a notification:

providers: [
provideCheckNoChangesConfig({ exhaustive: true, interval: 1000 }),
],

It throws ExpressionChangedAfterItHasBeenCheckedError when it finds a binding that zoneless change detection would not have refreshed. This is the highest-value thing you can turn on during a zoneless migration: it converts “some screens are subtly stale” into a loud, located error. Development configuration only — it is a diagnostic, not a production setting.

Change-detection performance is a product of two numbers: how often passes run and how expensive each pass is. Optimise the one that is actually large.

Reducing frequency. Going zoneless is the big lever, because it removes every pass that ZoneJS triggered speculatively. After that, the remaining sources are your own notifications, and signals are naturally frugal — a signal write that produces an equal value (Object.is) does not notify at all.

Reducing per-pass cost. Angular evaluates all template expressions in checked components and runs ngDoCheck, ngOnChanges, ngAfterContentChecked and ngAfterViewChecked, sequentially. A single slow computation therefore delays the entire pass. The official remedies, roughly in order of preference:

  1. Fix the algorithm. Speeding up the computation speeds up every pass that touches it.
  2. computed signals. Memoised, lazy, and dependency-tracked — the modern default for derived values.
  3. Pure pipes. Angular re-evaluates a pure pipe only when its inputs change. Still the right tool for a transformation applied across many rows.
  4. Memoisation. More general than a pure pipe, which caches only the most recent result — but watch the memory cost if you call it with many distinct arguments.
  5. Avoid repaints and reflows in lifecycle hooks. Reading offsetHeight or getBoundingClientRect in ngAfterViewChecked forces synchronous layout on every check.

Shrink the dirty view. Because signals mark whole views, a component whose template mixes a fast-changing value with a large static block re-renders the large block too. Splitting the fast-changing part into its own small child component confines the work.

Defer what is off-screen. @defer keeps components out of the tree — and therefore out of every pass — until they are needed. @defer (on viewport) is the cheapest possible optimisation for below-the-fold content: it reduces both bundle size and per-pass cost at once.

Change detection is not a security boundary, and it is worth being explicit because the mistake is common.

Hiding an element with @if (isAdmin()) removes it from the DOM. It does not remove the data from the JavaScript heap, the bundle, or the network response that populated it. Anyone can read it in DevTools. Every authorisation decision must be enforced server-side; client-side conditionals are presentation only.

The related mistake is putting a permission check in a template expression that calls a service method — it re-executes on every check, which is both a performance problem and, if it triggers a network request, an accidental request amplifier.

The testing implications are direct enough to state here, with the full picture on the testing page.

TestBed uses Zone-based change detection when zone.js is loaded via polyfills, and runs zoneless when it is not. To force zoneless behaviour while zone.js is still present, add the provider explicitly:

TestBed.configureTestingModule({
providers: [provideZonelessChangeDetection()],
});
const fixture = TestBed.createComponent(OrdersPortal);
await fixture.whenStable();

Prefer await fixture.whenStable() over fixture.detectChanges(). detectChanges() forces a pass Angular might never have scheduled, so a test using it can pass against a component that is broken in production. whenStable() lets Angular decide, which is exactly the property you want to be testing.

Angular is pragmatic about existing suites: converting thousands of detectChanges() calls is likely not worth the effort, because TestBed still enforces OnPush compatibility and throws ExpressionChangedAfterItHasBeenCheckedError when template values were updated without a notification. If that fires on a component used in production, fix the component — signals or markForCheck(). If it fires on a test-only wrapper component that no application ever renders, calling fixture.changeDetectorRef.markForCheck() is acceptable.

Decision Favours Costs
Zoneless (v21+ default) Smaller bundle, faster startup, clearer stacks, better ecosystem fit Zone-dependent code fails silently; libraries may lag
Staying on ZoneJS Legacy code keeps working untouched Speculative passes, larger bundle, permanent patching tax
OnPush (v22+ default) Whole subtrees skipped; forces explicit data flow Mutation-based code breaks; needs immutable updates or signals
Eager Tolerates mutation; needed by some library host components Checked on every traversal that reaches it
Signals for state Fine-grained, framework-independent notification Migration effort; a different reactivity model to learn
AsyncPipe over manual subscribe Automatic markForCheck() and unsubscribe Less control over emission timing
detach() / manual CD Maximum control for hand-driven rendering You own correctness; easy to leave views permanently stale

The honest summary: modern Angular moves the cost from runtime to authoring. You write more explicit code and get fewer speculative passes and fewer mystery bugs.

“A colleague says OnPush is an optimisation you opt into. Correct them.” That was true through Angular 21. From v22, OnPush is the default and the old Default strategy is renamed Eager and deprecated. The framing has inverted: eager checking is now the opt-in, for the cases that need it — typically library components that host arbitrary user components via ViewContainerRef.createComponent, which cannot assume their children are OnPush-compatible.

“A signal updates but the template doesn’t. Walk through your diagnosis.” Confirm the template actually reads the signal — reading it only in TypeScript registers no view as a consumer. Then check whether the write produced an equal value; signals compare with Object.is, so mutating an array in place and calling set with the same reference notifies nothing. Then check the view is attached and not detach()ed. Then check for a lingering provideZoneChangeDetection() masking the real behaviour in some environments but not others.

“How do you find out whether an application is safe to go zoneless?” Static pass first: grep for NgZone.onStable, onMicrotaskEmpty, onUnstable, isStable — those fail silently, so they are the dangerous ones. Then enable provideCheckNoChangesConfig({ exhaustive: true, interval }) in development and exercise the app; it converts silent staleness into thrown errors with a location. Then audit reactive-forms-driven templates specifically, since form model updates do not schedule change detection. Then run the test suite with the zoneless provider forced.

“Idle page, 30% CPU. What do you do?” Angular DevTools profiler, record while idle. If passes are firing with no interaction, read what triggered them. Repeating setTimeout/requestAnimationFrame/event-handler sources on a ZoneJS app is zone pollution — find the library and initialise it in runOutsideAngular. If there are few passes but each is long, it is a slow computation instead: click the bar for the per-component breakdown and check for method calls in templates and work in ngDoCheck/ngAfterViewChecked.

“Why does ExpressionChangedAfterItHasBeenCheckedError only appear in development?” Development builds run an extra verification pass after change detection and compare the bindings. If a value differs, the rendered output depended on how many times the pass ran — a real bug, not a dev-mode artefact. Production skips the check for speed, so the bug becomes a silently stale or inconsistent view instead of an error. Never “fix” it by suppressing it.

“Your list re-renders entirely on every WebSocket message. Why?” Most likely the track expression. Without a stable identity, @for cannot match new items to existing DOM nodes and destroys and recreates the rows — losing focus, scroll position and component state. Track a stable domain key. The secondary cause is replacing the whole collection when only one item changed; keep the list stable and update in place through a signal so only the affected row’s view is marked.