What is the difference between the change detection strategies OnPush and Default? Why use OnPush?
sobes.tech AI
Answer from AI
In Angular, the change detection strategy determines when and how Angular checks components for changes and updates the DOM.
Default — this is the standard strategy where Angular checks the component and all its child components on any event that might change the state (e.g., user event, timer, HTTP request, etc.). This ensures data freshness but can lead to excessive checks and reduced performance.
OnPush — an optimized strategy where Angular checks the component only if:
- an input (@Input) has changed (by reference),
- an event occurs inside the component,
- or the
markForCheck()method is called manually.
Using OnPush can significantly reduce the number of checks, improving application performance, especially with many components and complex trees. It requires data to be immutable or updated through new objects so Angular can detect changes by reference.
Example:
@Component({
selector: 'my-comp',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `{{data.name}}`
})
export class MyComponent {
@Input() data: { name: string };
}
If the parent replaces data with a new object, the component will update; if only the name field of the same object changes, no update will be visible.
Summary: OnPush is used to improve performance when immutability of input data can be guaranteed and updates are controlled manually.