Performance: OnPush change detection strategy
This affects how often Angular checks and updates the component's view, impacting rendering speed and responsiveness.
Jump into concepts and practice - no test required
import { Component, ChangeDetectionStrategy, Input } from '@angular/core'; @Component({ selector: 'app-example', template: `<p>{{ counter }}</p>`, changeDetection: ChangeDetectionStrategy.OnPush }) export class ExampleComponent { @Input() counter = 0; }
import { Component } from '@angular/core'; @Component({ selector: 'app-example', template: `<p>{{ counter }}</p>` }) export class ExampleComponent { counter = 0; // Default change detection strategy (CheckAlways) }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Default (CheckAlways) | Many unnecessary DOM checks | Multiple reflows on unrelated changes | Higher paint cost due to frequent updates | [X] Bad |
| OnPush Change Detection | Checks only on input or event changes | Minimal reflows limited to actual changes | Lower paint cost with fewer updates | [OK] Good |
OnPush change detection strategy do in Angular?OnPush change detection strategy in an Angular component?changeDetection and the value is ChangeDetectionStrategy.OnPush.OnPush strategy:@Component({
selector: 'counter',
template: `{{count}}`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class CounterComponent {
@Input() count = 0;
}
count from 0 to 1, what will happen?count from parent triggers view update.OnPush strategy. Inside it, you update a local variable without changing any input. The view does not update. What is the likely cause?detectChanges() manually for every change. is sometimes needed but not always. The component must use Default strategy to update local variables. is incorrect; Default strategy is not required for local updates.OnPush strategy. The parent updates a property inside the object without changing the object reference. Will the child detect the change and update its view?markForCheck() manually. is partially true but not automatic. No, because OnPush disables all change detection for objects. is incorrect; OnPush does not disable detection for objects.