Performance: When to use OnPush
OnPush affects how Angular detects changes and updates the DOM, impacting rendering speed and responsiveness.
import { Component, ChangeDetectionStrategy, Input } from '@angular/core'; @Component({ selector: 'app-good', changeDetection: ChangeDetectionStrategy.OnPush, template: `<p>{{data.name}}</p>` }) export class GoodComponent { @Input() data!: { name: string }; }
import { Component } from '@angular/core'; @Component({ selector: 'app-bad', template: `<p>{{data.name}}</p>` }) export class BadComponent { data = { name: 'Angular' }; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Default Change Detection | Runs on all events and async tasks | Multiple reflows per event | Higher paint cost due to frequent updates | [X] Bad |
| OnPush Change Detection | Runs only on input reference changes or events | Minimal reflows | Lower paint cost with fewer updates | [OK] Good |
ChangeDetectionStrategy.OnPush in an Angular component?@Component({
selector: 'app-counter',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `{{count.value}}`
})
export class CounterComponent {
@Input() count = {value: 0};
}count by mutating an object property instead of replacing the input?items.push(newItem). The child does not update. How should you fix this to ensure the child updates efficiently?items = [...items, newItem] creates a new array reference, triggering OnPush change detection in the child.items = [...items, newItem] to create a new array reference -> Option APass the test and this pattern moves unknown