Sobes.tech
Middle

What is Change Detection in Angular? What strategies exist?

sobes.tech AI

Answer from AI

Change Detection in Angular is a mechanism that monitors changes in the data model and updates the view (DOM) accordingly.

When the component data changes, Angular runs a change detection process to determine which parts of the interface need updating.

There are two main change detection strategies:

  1. Default — Angular checks all components in the tree, starting from the root, on every event, timer, or asynchronous call. This ensures data freshness but can be less performant with a large number of components.

  2. OnPush — Angular checks the component only if:

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

This strategy improves performance by reducing the number of checks, especially in large applications.

Example of using OnPush:

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

Here, Angular will update the component only if the reference to data changes, not when properties inside the object change without changing the reference.

What is Change Detection in Angular? What strategies… - sobes.tech