🅰️ Angular Intermediate

What is Angular change detection with OnPush strategy?

Why Interviewers Ask This

This question targets practical, hands-on experience with Angular. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.

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.

Common Mistake

Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real Angular project.