Angular · Lesson 4

Change detection

How Angular decides what to re-render. What a check does, zone.js and why it triggers checks, `OnPush`, `markForCheck` and immutability, signal-based and zoneless change detection (the default for new apps since Angular 21), `ExpressionChangedAfterItHasBeenChecked`, and performance tips.

11 min read

In short

  • A check re-evaluates bindings and compares with Object.is
  • zone.js checks the whole tree after every async task
  • OnPush skips a component unless it has a reason
  • Signals and zoneless refresh only the marked views
  • Replace values, never mutate; avoid manual subscribe

Change detection keeps the DOM in sync with your components: Angular re-evaluates template bindings and updates the DOM where a value changed. Three everyday questions are really questions about it: "why didn't my view update?", "why is this page slow?", and "what is ExpressionChangedAfterItHasBeenCheckedError?".

Angular has changed here more than anywhere else. Apps built before Angular 21 usually run on zone.js and check the whole tree after every event; new apps are zoneless and only check what signals and events tell them to. On a team you'll meet both, often in the same codebase during a migration, so this lesson covers both and the rules that connect them. The exercises rebuild each piece: the binding check, SimpleChanges, the async pipe, the dev-mode second pass, the OnPush/signals tree walk, and a zone.

What a check does

Each component's template compiles to a function with two parts: create (build the DOM once) and update (run on every check). The update part evaluates every binding, compares it with the previous value using Object.is, and touches the DOM (or sets a child's input) only when it changed:

▶ Try
// What the update code does for: <h2>{{ title }}</h2> <span>{{ items.length }} items</span> <app-list [items]="items" />
const previous: unknown[] = [];
let domWrites = 0;

function bindingChanged(index: number, value: unknown): boolean {
  if (Object.is(previous[index], value)) return false;
  previous[index] = value;
  domWrites++;
  return true;
}

function check(component: { title: string; items: string[] }) {
  bindingChanged(0, component.title);
  bindingChanged(1, component.items.length);
  bindingChanged(2, component.items); // the child's input
}

const page = { title: 'Cart', items: ['tea'] };
check(page);
console.log('first check, writes:', domWrites);              // 3
page.items.push('cake');                                       // mutation
check(page);
console.log('after push, writes:', domWrites);               // 4: the length changed, the array reference did not
page.items = [...page.items, 'scones'];                        // new array
check(page);
console.log('after replacing the array, writes:', domWrites); // 6

A check runs top-down through the component tree, synchronously, and calls the lifecycle hooks along the way (see the Components & templates topic for the order). The question is when it runs and which components it visits.

zone.js: "something happened, check everything"

Before signals, Angular couldn't know which state changed, so it watched for anything that might have changed state. zone.js patches the browser's async APIs (setTimeout, setInterval, promises, addEventListener, XHR and fetch), so Angular is told when every task finishes. After each one (when no microtasks are left) NgZone emits onMicrotaskEmpty, and Angular calls ApplicationRef.tick(), which checks the tree from the root.

That's why this works in a zone app for an Eager component, without any notification:

import { ChangeDetectionStrategy, Component } from '@angular/core';

@Component({
  selector: 'app-clock',
  changeDetection: ChangeDetectionStrategy.Eager, // the default before Angular 22
  template: `{{ time }}`,
})
export class Clock {
  time = new Date().toLocaleTimeString();

  constructor() {
    setInterval(() => (this.time = new Date().toLocaleTimeString()), 1000);   // zone.js: tick after every run
  }
}

The cost: every mousemove, scroll, timer and HTTP response checks the whole app, even when nothing in the view changed. Tools for zone apps:

  • inject(NgZone).runOutsideAngular(() => ...): work started there (a polling timer, a chart library, a websocket heartbeat) doesn't trigger checks. Call ngZone.run(() => ...) to re-enter when you do need an update.
  • provideZoneChangeDetection({ eventCoalescing: true }) merges the checks for events that fire together.
  • A zone app is "stable" (ApplicationRef.isStable) only when no zone timers are pending. A setInterval started in the zone keeps it unstable forever, which breaks server-side rendering and hydration timing, and whenStable() in tests.

Exercise 6 builds a zone.

Default vs OnPush

import { ChangeDetectionStrategy, Component, input } from '@angular/core';

@Component({
  selector: 'app-order-row',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `{{ order().id }}: {{ order().total }}`,
})
export class OrderRow {
  readonly order = input.required<{ id: string; total: number }>();
}
  • Default (called Eager since Angular 21.2, where Default became deprecated): checked every time a check reaches it.

  • OnPush: checked only when one of these happened since its last check:

    1. an input bound in its parent's template got a new value (Object.is, so a new reference),
    2. an event handler in its template (or a child's) ran,
    3. it was marked with markForCheck() (the async pipe does this),
    4. a signal it reads in its template changed.

    Otherwise Angular skips it and its whole subtree (unless a signal marked something inside it, see below). That's the performance win: a list of 500 OnPush rows is skipped in one comparison per row when nothing changed.

  • From Angular 22, OnPush is the default for components, and ng update adds ChangeDetectionStrategy.Eager to existing components that relied on the old default. In Angular 20 and 21 you set OnPush yourself, and most teams do it everywhere (often via a lint rule or schematic default).

The price of OnPush is that you follow its rules. Mutation is invisible to it:

// In the parent component (not runnable here):
this.order.total = 99;                          // same object: OrderRow is NOT checked, it shows the old total
this.order = { ...this.order, total: 99 };      // new object: OrderRow's input changed, it updates

markForCheck, detectChanges and immutability

  • inject(ChangeDetectorRef).markForCheck() marks the component and all its ancestors as dirty, so the next check visits them. Use it when a non-signal value changed for reasons Angular can't see (a callback from a library, a manual subscription).
  • detectChanges() runs a check of this component and its children right now, synchronously. You rarely need it; it's mostly for tests and for code that must read the updated DOM immediately.
  • The async pipe subscribes, stores the latest value, and calls markForCheck() on every emission. That's why {{ user$ | async }} works in OnPush components, and why a manual subscribe that assigns a field doesn't:
import { ChangeDetectionStrategy, Component, OnInit, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';

@Component({
  selector: 'app-notifications',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `{{ count }} / {{ count$ | async }} / {{ countSignal() }}`,
})
export class Notifications implements OnInit {
  private readonly service = inject(NotificationService);
  count = 0;                                              // updated, but never shown: nobody marks the view
  readonly count$ = this.service.count$;                  // async pipe: marks the view on each value
  readonly countSignal = toSignal(this.service.count$, { initialValue: 0 }); // signal: marks the view

  ngOnInit() {
    this.service.count$.subscribe((n) => (this.count = n));   // the classic OnPush bug
  }
}

Exercise 3 builds the async pipe.

Signals: checking only what changed

When a component's template reads a signal, the template itself is a reactive consumer. When that signal changes, Angular marks just that component's view for refresh, and marks its ancestors only so the check knows which way to go down. On the next check, ancestors whose own state didn't change are traversed, not re-checked; only the component that reads the signal re-runs its template. (In a zone.js app that's true for OnPush ancestors; Eager ones are checked on every pass anyway. A zoneless app refreshes the marked views and the Eager components inside them, and only traverses the rest.)

So with signals and OnPush, a counter in a deep component updates one component, not the tree, and you don't need markForCheck or immutability tricks for state held in signals (you still need new references for arrays and objects inside signals; see the Signals topic).

Zoneless: the default for new apps since Angular 21

import { bootstrapApplication } from '@angular/platform-browser';
import { provideZonelessChangeDetection } from '@angular/core';

// Angular 21+: zoneless is the default, this line is only needed on older versions.
// A zone.js app instead uses provideZoneChangeDetection() and loads zone.js in its polyfills.
bootstrapApplication(App, { providers: [provideZonelessChangeDetection()] });

Without zone.js, Angular doesn't know when a timer fires or a promise resolves. It schedules a check only when something notifies it:

  • a signal read in a template changes,
  • markForCheck() is called (including by the async pipe),
  • a template or host event listener runs,
  • ComponentRef.setInput() is called,
  • a view is attached or removed (for example by @if or the router).

And then it only refreshes the parts of the tree that were marked. What stops working: assigning a plain field in a setTimeout, a subscribe callback or after an await and expecting the view to update. (The Clock component above freezes.) NgZone.onStable/onMicrotaskEmpty never emit, and NgZone.isStable is always true; use afterNextRender or afterEveryRender instead.

Migrating a zone app: make components OnPush-compatible (signals, async pipe, toSignal, markForCheck), and the switch to zoneless is mostly removing zone.js. Components that already work with OnPush almost always work zoneless. Benefits: smaller bundles, no patched browser APIs (better stack traces), and fewer, cheaper checks.

Tests: TestBed is zoneless by default since Angular 21. Prefer await fixture.whenStable() over fixture.detectChanges(), so the test proves the component notifies Angular properly. Exercise 5 simulates which components a check visits, with zones and without.

ExpressionChangedAfterItHasBeenCheckedError (NG0100)

In development mode, after each check Angular runs a second, verification pass that re-evaluates the bindings of the Eager components it just checked. If any value is different, it throws NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked, with the previous and current values in the message. OnPush components (the default since Angular 22) are skipped unless you turn on provideCheckNoChangesConfig({ exhaustive: true }), so in them the same bugs just leave a stale value on screen.

It means data flowed backwards during the check: something changed a value that Angular had already rendered, so the screen is now out of date and one pass wasn't enough. Typical causes:

  • A child changes parent state during the check: in ngOnInit/ngAfterViewInit, or by emitting an output that the parent handles synchronously during that check (a "loading" flag the child sets when it starts).
  • A binding that returns a different value every time: Date.now(), Math.random(), or an array whose items change. (A new object every time doesn't throw: the verification compares arrays item by item but treats any two objects as equal. It's still wasted work on every check.)
  • Code in ngAfterViewInit that reads the DOM or a query and stores a value the template shows.

Fixes, in order of preference: derive the value instead of setting it (computed); compute it earlier (constructor, ngOnInit of the owner); keep it in a signal (a signal written during a check marks the view for refresh, and Angular re-runs the check for it instead of throwing, up to a limit after which it reports NG0103, infinite change detection); or restructure so the data flows down. Wrapping the assignment in setTimeout makes the error go away and adds a second check plus a visible flicker: avoid it. The verification pass never runs in production, which is why the bug "only happens in dev" while production quietly shows stale values. Exercise 4 builds the check.

Performance tips

  • OnPush everywhere, state in signals, and immutable updates.
  • Cheap templates: computed signals or pure pipes instead of method calls that do work; no new objects or arrays built in bindings.
  • @for with track item.id, so updates reuse rows.
  • @defer heavy components that aren't visible yet.
  • Zone apps: run noisy third-party code and polling outside Angular, enable event coalescing, and move to zoneless.
  • Long lists: paginate, or virtual-scroll with the CDK's cdk-virtual-scroll-viewport.
  • Measure with the Angular DevTools profiler: it shows each change detection cycle, what triggered it and the time per component.

Common mistakes

  • Mutating an input object or array of an OnPush component (or a signal's value). Replace it.
  • Manual subscribe that assigns a field in an OnPush or zoneless component. Use toSignal, the async pipe, or a signal.
  • detectChanges() sprinkled to "fix" updates: it hides the real problem (missing notification) and costs a synchronous check every time.
  • setTimeout(() => ...) to silence NG0100: fix the data flow instead.
  • Heavy getters in templates: they run on every check of that component.

Compared with React

ReactAngular
a state change re-renders that component and its childrena check re-evaluates bindings from the root (zone) or the marked components (signals, zoneless)
React.memo (skip if props are shallow-equal)OnPush (skip unless an input reference changed or the component was marked)
useState setter schedules a rendera signal set marks the component for refresh
Strict Mode double-invokes to find impure rendersthe dev-mode verification pass finds unstable bindings (NG0100)

The exercises

  1. The binding check: Object.is comparisons per binding, and what that means for mutation.
  2. SimpleChanges: which inputs changed, with firstChange, and when an OnPush child gets checked.
  3. The async pipe: subscribe, switch sources, markForCheck, and clean up, with real RxJS.
  4. ExpressionChangedAfterItHasBeenChecked: the dev-mode verification pass, and why signals are re-checked instead.
  5. Which components get checked?: Default, OnPush, markForCheck, events, signals, with zone.js and zoneless.
  6. A zone: track tasks, notify when the microtask queue empties, run outside Angular, and wait until stable.

Practise this lesson

In the app: a short video, 6 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.

Open in the app