Sobes.tech
Middle

How does the Change Detection mechanism work in Angular?

sobes.tech AI

Answer from AI

The Change Detection mechanism in Angular is responsible for tracking data changes and updating the DOM when necessary.

Angular uses a zone (NgZone) to intercept asynchronous events (such as clicks, HTTP requests). After such events, a change detection cycle is triggered, which checks the values of bound component properties.

Angular compares the current values with previous ones (by reference or by value, depending on the strategy) and updates the view if changes are detected.

There are two Change Detection strategies:

  • Default: checks all components in the tree
  • OnPush: checks a component only if its input data has changed or an event has occurred inside the component

This helps optimize performance by reducing the number of checks.

Example:

@Component({
  selector: 'app-example',
  template: `{{counter}}`
})
export class ExampleComponent {
  counter = 0;

  increment() {
    this.counter++;
  }
}

When increment() is called, Angular detects the change in counter and updates the display.