Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 74 ยท Signals and Reactivity

Change Detection, OnPush and Zoneless

Understand how Angular decides when to update the page - Zone.js, the Default and OnPush strategies, markForCheck, signals and zoneless change detection - with runnable stand-ins.

Change detection is the mechanism that keeps the page in step with your data. When a user clicks a button, a timer fires or an HTTP response arrives, your code changes some state, and Angular has to find out which parts of the page now show something different and update them. The question is always the same: when do we look, and where?

Angular has three answers, and a modern app mixes them. The classic one is Zone.js with the Default strategy: after almost any asynchronous event, check every component. The refinement is OnPush: skip components that have no reason to have changed. The newest is signal-driven and zoneless: components that read signals in their template are updated precisely when those signals change, and nothing else runs. Understanding all three explains most performance advice and most "why did my view not update" mysteries.

Real versus stand-in. The typescript blocks are real Angular and read-only, because the site cannot run the Angular compiler. The runnable examples are hand-written models of the behavior: a tree of objects with check counters, and a tiny signal implementation. They show the idea, not Angular's actual algorithm.

Zone.js and the Default strategy

Historically Angular used Zone.js, a library that patches browser APIs such as setTimeout, promises, DOM event listeners and XMLHttpRequest. After any patched task finishes, Zone.js tells Angular "something may have changed", and Angular calls ApplicationRef.tick(), which walks the component tree from the root and re-evaluates every template binding.

With the Default strategy every component is checked on every tick, top to bottom. This is simple and forgiving: you can mutate objects, reassign fields or push into arrays and the page catches up on the next event. The price is that a large app checks thousands of bindings after every mouse move you subscribed to, whether or not anything changed.

flowchart TD
  A["Event, timer or HTTP response"] --> Z["Zone.js notices (apps with zones)"]
  S["Signal read in a template changes<br/>or markForCheck() or a template event"] --> N["Change detection scheduler (zoneless)"]
  Z --> T["ApplicationRef.tick()"]
  N --> T
  T --> C["Check components top-down<br/>skip clean OnPush subtrees"]

Two ways to start a change detection pass. Both end in the same top-down check.

OnPush: check only when there is a reason

A component marked ChangeDetectionStrategy.OnPush is skipped, together with its whole subtree, unless it has been marked dirty. It becomes dirty when:

  • one of its inputs receives a new value (compared by reference, so a mutated object does not count);
  • an event fires from its own template or a host listener;
  • a signal read in its template changes;
  • an async pipe in its template receives a new emission;
  • code calls markForCheck() on its ChangeDetectorRef.
TypeScript
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, inject, input } from '@angular/core';

@Component({
  selector: 'app-item-list',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    @for (item of items(); track item) {
      <li>{{ item }}</li>
    }
    <p>Last refresh: {{ refreshedAt }}</p>
  `,
})
export class ItemListComponent {
  readonly items = input.required<string[]>();
  refreshedAt = '';

  private readonly cdr = inject(ChangeDetectorRef);

  setRefreshed(time: string): void {
    this.refreshedAt = time;      // a plain field: Angular is not told
    this.cdr.markForCheck();      // so we flag the component as dirty
  }
}

The consequence is a rule you may have heard: with OnPush, treat data as immutable. If a parent does items.push('x') the input keeps the same reference, so the component is not marked dirty and the list looks frozen. Replace the array (items = [...items, 'x']) and everything works. Plain fields that change outside those triggers need markForCheck(), which is why signals are such a relief: reading a signal in the template registers the dependency automatically.

The first stand-in models a tree with Default and OnPush components. Each component counts how often it was checked, and the Counter and List display the rendered text so you can see staleness.

TypeScript Dirty checking: Default and OnPush in a component tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Steps 2 and 4 are the classic traps: the data changed, the page shows the old text, and the check counters of Counter and List did not move. Steps 3 and 5 repair it, the first by flagging the component and the second by giving the input a new reference. Header was checked exactly once in the whole run, which is the saving OnPush offers.

flowchart TD
  App["App (Default): checked"] --> H["Header (OnPush): skipped"]
  App --> C["Counter (OnPush): checked, was marked dirty"]
  App --> L["List (OnPush): skipped"]

One tick after counter.markForCheck(): only dirty OnPush components and their ancestors are visited.

Signals and zoneless change detection

When a template reads a signal, Angular records that dependency. If the signal changes, Angular marks exactly that component for checking, much like an automatic markForCheck(). This works in both zone-based and zoneless apps, and it is why a component that holds all its state in signals behaves correctly even with OnPush.

Once everything notifies Angular itself, Zone.js is no longer needed. Zoneless change detection removes it: you remove zone.js from the build's polyfills, add the provider, and Angular schedules a pass only when a signal read by a template changes, a template event fires, markForCheck() is called, or an async-pipe emits. In Angular 20 the provider is provideZonelessChangeDetection(); it was in developer preview before and became stable in a 20.x release, and newer CLI versions generate zoneless apps by default, so check what your version does.

TypeScript
// app.config.ts
import { ApplicationConfig, provideZonelessChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideZonelessChangeDetection(),
    provideRouter(routes),
  ],
};

Zoneless brings smaller bundles, simpler stack traces and better compatibility with native async/await, which Zone.js could not patch. In return, a plain field that changes in a setTimeout will no longer update the view: put the state in a signal instead. Using OnPush everywhere is good practice now because it makes your components zoneless-ready.

The second stand-in shows signal-driven updates with a tiny implementation. There is no tree walk at all: each "component" is an effect that reads the signals it needs, so only the affected ones run.

TypeScript Signal-driven updates: no tree walk

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The summary line shows that Header rendered once, while Counter and List rendered only when their own signals changed. The in-place push did nothing, for the same reason as with OnPush inputs: the signal still holds the same array. There is no markForCheck() in sight, because reading a signal already declared the dependency.

Debugging change detection

  • Page does not update. In an OnPush or zoneless component, check that the changed value is a signal, a new input reference, or flagged with markForCheck(). A field changed inside setTimeout or a callback from a non-Angular library is the usual culprit.
  • NG0100: ExpressionChangedAfterItHasBeenChecked. In development mode Angular runs a second pass to verify that nothing changed during the first. If a binding's value differs, it throws. It typically means state was modified while the view was being checked, for example in ngAfterViewInit or by a child that changes a parent's value. Move the change earlier, derive the value with computed(), or schedule it with afterNextRender, see Lifecycle Hooks and afterNextRender.
  • Too much work. Angular DevTools has a profiler tab that records change detection cycles and shows which components were checked and for how long. Pair it with OnPush, signals and track expressions, covered in Performance Tuning.
  • Code outside Angular. Heavy third-party code in a zone-based app can run in NgZone.runOutsideAngular() so it does not trigger a tick on every event. Zoneless apps do not need this.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Zone.js do in a classic Angular application?

    Zone.js wraps timers, promises, events and network calls. When one completes, Angular is notified and calls tick() to check the component tree.
  2. 2. A parent calls this.items.push('x') on an array passed to an OnPush child through an input. What happens?

    OnPush compares inputs by reference. A mutated array keeps its identity, so replace it with a new array instead.
  3. 3. Which of these marks an OnPush component for checking?

    Signals read in a template register a dependency, so Angular marks the component dirty when they change. Plain fields need markForCheck().
  4. 4. What is a benefit of zoneless change detection?

    Zoneless apps run change detection only when notified by signals, events, markForCheck or the async pipe. That removes Zone.js, but state that changes silently still must be a signal.
  5. 5. What usually causes NG0100 ExpressionChangedAfterItHasBeenChecked?

    In dev mode Angular checks twice, and a binding that produced a different value the second time raises the error. Move the change earlier or derive it with computed().

Summary

  • Change detection decides when and where Angular re-evaluates template bindings.
  • Zone.js plus the Default strategy checks every component after any async task; simple but wasteful in large trees.
  • OnPush skips a component unless an input reference changed, an event fired, a read signal changed, an async pipe emitted or markForCheck() ran, so use immutable data.
  • Signals make updates precise, and provideZonelessChangeDetection() removes Zone.js entirely; keep changing state in signals.
  • NG0100 means state changed during the check; fix it by deriving or moving the change.

Next: Services and Dependency Injection.