61. Change Detection Strategy: Default vs OnPush
Change Detection (CD) is Angular's process of checking the application state to see if any data has changed, and if so, updating the view (DOM) accordingly. This check happens very frequently.
1. Default Change Detection Strategy (ChangeDetectionStrategy.Default)
In the default strategy, Angular is essentially pessimistic. It assumes that any data property used in the template might have changed, regardless of the cause. A CD cycle is triggered by:
- Any DOM event (click, keyup).
- HTTP responses.
- Timers (
setTimeout,setInterval). - Promises resolved.
When a change happens anywhere, Angular checks all components, from root to leaf, recursively. While fast, this can become a bottleneck in very large applications.
2. OnPush Change Detection Strategy (ChangeDetectionStrategy.OnPush)
OnPush is the optimistic approach. A component marked OnPush will only run change detection (check its template and trigger checks on its children) if one of the following occurs:
- Input Reference Change: A component's input property (
@Input()) changes its reference (i.e., the memory address of the object/array is different). Changes inside an object (mutation) are ignored. - An Event Fired: An event handler attached to the component or its children runs.
- Observable Emission (with
AsyncPipe): An Observable bound via theAsyncPipeemits a new value. - Manual Trigger: Change detection is manually triggered using
ChangeDetectorRef.
Applying OnPush
typescript import { Component, ChangeDetectionStrategy } from '@angular/core';
@Component({ selector: 'app-optimized-list', templateUrl: './optimized-list.component.html', changeDetection: ChangeDetectionStrategy.OnPush // <-- Use this }) export class OptimizedListComponent { /* ... */ }
OnPush greatly improves performance by skipping large branches of the component tree unless explicitly notified of a change.