Sobes.tech
Middle

What is Change Detection in Angular and how does the OnPush strategy differ from the default strategy?

sobes.tech AI

Answer from AI

Change Detection in Angular is a mechanism that tracks changes in component data and updates the DOM to reflect the current state of the application. Angular automatically checks components for changes and updates the view when data changes.

The default strategy means that Angular checks the component and all its child components on every event, timer, or asynchronous call, which can be performance-intensive.

The OnPush strategy optimizes performance by making Angular check the component only if:

  • an input (@Input) has changed (reference comparison),
  • an event occurs inside the component,
  • or the detectChanges method is called manually.

This reduces the number of checks and improves performance, especially in large applications.

Example of using OnPush:

@Component({
  selector: 'my-component',
  template: `{{data.name}}`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {
  @Input() data: { name: string };
}

Here, Angular will update the component only if the reference to data changes.

What is Change Detection in Angular and how does the… - sobes.tech