TExcelTAD
Home › Angular › Change Detection

Change Detection

Change detection is how Angular keeps the page in sync with your data. When something might have changed, Angular walks the component tree, re-evaluates template bindings and updates the DOM where values differ. Understanding when and which components are checked helps you write fast apps and explains some surprising bugs.

Two questions

Every change detection system must answer:

  1. When should we check? — after a click, a timer, an HTTP response…
  2. What should we check? — the whole tree, or only components that could be affected?

When: zone.js vs zoneless

Historically, Angular used a library called zone.js that patches browser APIs (setTimeout, event listeners, fetch, …). After any of them ran, zone.js told Angular "something async happened" and Angular checked the app.

Modern Angular can run zoneless: instead of patching the browser, Angular schedules change detection when it is told something changed:

Trigger Schedules a check (zoneless)
A signal read by a template is set ✅
A bound template event handler runs ((click), …) ✅
markForCheck() is called (e.g. by the async pipe) ✅
A component input changes ✅
A plain field is changed inside setTimeout ❌ — nothing tells Angular

New projects created with recent CLI versions are zoneless (provideZonelessChangeDetection() in app.config.ts). That's one more reason to keep UI state in signals.

angular · try it yourself
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-timer-demo',
  template: `
    <p>Plain field: {{ plainCount }}</p>
    <p>Signal: {{ signalCount() }}</p>
  `,
})
export class TimerDemo {
  plainCount = 0;
  signalCount = signal(0);

  constructor() {
    setTimeout(() => {
      this.plainCount = 1;      // zoneless: Angular is not notified
      this.signalCount.set(1);  // notifies Angular → re-render
      console.log('both set to 1');
    }, 1000);
  }
}
both set to 1

Here the plain field happens to show 1 as well — because the signal update triggered a re-render of the whole component. If you only changed plainCount, the page would keep showing 0. Relying on such side effects is fragile: put displayed state in signals.

What: Default vs OnPush

With the Default strategy, every component in the tree is checked on each pass. With OnPush, a component (and its subtree) is checked only when:

  • one of its inputs receives a new reference,
  • an event handler in its template fires,
  • a signal it reads in its template changes,
  • or it is explicitly marked with ChangeDetectorRef.markForCheck() (the async pipe does this).
ts
@Component({
  selector: 'app-price-tag',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `{{ price() | currency }}`,
})
export class PriceTag {
  price = input.required<number>();
}

OnPush lets Angular skip whole branches of the tree. With signals and immutable inputs, OnPush works naturally and is a sensible default for every component.

Simulating a check pass

The cost of change detection is the number of bindings evaluated. This plain TypeScript simulation walks a component tree and skips OnPush components that aren't dirty:

ts · try it yourself
interface Cmp {
  name: string;
  onPush: boolean;
  dirty: boolean;
  bindings: number;
  children: Cmp[];
}

const cmp = (name: string, onPush: boolean, bindings: number, children: Cmp[] = []): Cmp =>
  ({ name, onPush, dirty: false, bindings, children });

const tree = cmp('App', false, 3, [
  cmp('Header', true, 4),
  cmp('ProductList', true, 2, [cmp('ProductCard', true, 6), cmp('ProductCard', true, 6)]),
  cmp('Footer', true, 2),
]);

function check(c: Cmp, visited: string[]): number {
  if (c.onPush && !c.dirty) return 0;   // skip this whole subtree
  visited.push(c.name);
  c.dirty = false;
  return c.bindings + c.children.reduce((n, ch) => n + check(ch, visited), 0);
}

const all = (c: Cmp): Cmp[] => [c, ...c.children.flatMap(all)];

// Pass 1: everything dirty (first render)
all(tree).forEach((c) => (c.dirty = true));
let visited: string[] = [];
console.log('first render bindings:', check(tree, visited), visited.length, 'components');

// Pass 2: only the second card's signal changed (its ancestors are marked too)
tree.children[1].dirty = true;
tree.children[1].children[1].dirty = true;
visited = [];
console.log('update bindings:', check(tree, visited), visited.join(' > '));
first render bindings: 23 6 components
update bindings: 11 App > ProductList > ProductCard

On the update only 3 of 6 components are visited. Real Angular is even smarter with signals: it can refresh just the component whose signal changed.

Practical rules

Do Avoid
Keep template state in signals Mutating plain fields in async callbacks
Use ChangeDetectionStrategy.OnPush Expensive method calls in templates ({{ compute() }})
Pass new objects/arrays to inputs Mutating an input object in place
Use computed() / pure pipes for derived values Doing heavy work in ngDoCheck

Tip: In development mode Angular checks twice and throws ExpressionChangedAfterItHasBeenCheckedError if a binding changed during the check. It usually means a value is being modified while rendering — move that logic into a computed() or an event handler.

Test yourself

In a zoneless app, which change reliably triggers a re-render?

  1. Setting a plain class field inside setTimeout
  2. Setting a signal that the template reads
  3. Changing a global variable
  4. Logging to the console

When is an OnPush component checked?

  1. On every change detection pass
  2. Only when its inputs change by reference, an event fires in it, a signal it reads changes, or it is marked for check
  3. Never after the first render
  4. Only when the route changes

What did zone.js do for Angular?

  1. Compiled templates
  2. Patched async browser APIs to tell Angular when to run change detection
  3. Provided routing
  4. Minified the bundle