🅰️ Angular Intermediate

What is Angular change detection with OnPush strategy?

Answer

The OnPush change detection strategy (ChangeDetectionStrategy.OnPush) is an optimization that restricts when Angular checks a component for changes, reducing the number of DOM updates. Default strategy (CheckAlways): Angular checks ALL components every time ANY async event fires (click, timer, HTTP response). For large component trees, this is expensive. OnPush triggers: a component with OnPush is only checked when: (1) An @Input() reference changes (primitive value changes or new object/array reference — mutation doesn't trigger); (2) An event originated from the component or its children (user click inside the component); (3) An Observable used with the async pipe emits a new value; (4) changeDetectorRef.markForCheck() is called manually. Implementation: @Component({ changeDetection: ChangeDetectionStrategy.OnPush }). Immutability requirement: OnPush only detects reference changes. You must create new arrays/objects instead of mutating: this.items = [...this.items, newItem] (triggers) vs this.items.push(newItem) (doesn't trigger). Use spread operator, Object.assign(), or immutable libraries. Manual triggering: when a service changes data (not through an Observable), use: this.cdr.markForCheck() — schedules the component for check in the next cycle; this.cdr.detectChanges() — runs change detection immediately synchronously. Signals (Angular 16+): the new reactivity model — fine-grained change detection that doesn't require OnPush manually; signals automatically track which views depend on which signals.