Back to all posts

Angular Change Detection


1. What is Change Detection?

Change detection in Angular is the process of synchronizing the model (component state) with the view (DOM). When data in a component changes, Angular determines what parts of the DOM need to be updated and updates them efficiently.

Angular uses a unidirectional data flow and a tree-based change detection mechanism. Here’s how it works:

  • Each component in Angular has its own change detector.
  • When an event occurs (e.g., user input, HTTP response), Angular runs change detection starting from the root component and propagates downward.
  • Angular checks component bindings to see if they have changed and updates the view accordingly.

Angular primarily uses Zone.js to detect asynchronous changes (like event handlers, setTimeout, HTTP calls) and trigger change detection.

Change Detection Strategies

There are two main change detection strategies in Angular:

  1. Default (ChangeDetectionStrategy.Default)
    • The entire component tree is checked when any change happens.
    • Works well for small applications but can be inefficient for larger ones.
  2. OnPush (ChangeDetectionStrategy.OnPush)
    • Only runs change detection when the component’s @Input() values change or an event occurs inside the component.
    • Ideal for performance optimization, especially when working with immutable data or observables.




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

@Component({
  selector: 'app-child',
  template: `<p>{{ data }}</p>`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent {
  @Input() data!: string;
}