0
0
Angularframework~5 mins

Default change detection strategy in Angular

Choose your learning style9 modes available
Introduction

The default change detection strategy in Angular automatically updates the view whenever data changes. It helps keep the screen in sync with the app's data without extra work.

When you want Angular to check for changes in all components automatically.
When your app has simple data flows and you want easy updates.
When you do not need to optimize performance for large or complex apps.
When you want Angular to detect changes on every event like clicks or HTTP responses.
Syntax
Angular
import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-example',
  template: `<p>{{ message }}</p>`,
  changeDetection: ChangeDetectionStrategy.Default
})
export class ExampleComponent {
  message = 'Hello!';
}

The default strategy is ChangeDetectionStrategy.Default.

You do not have to set it explicitly because Angular uses it by default.

Examples
This sets the component to use the default change detection strategy.
Angular
changeDetection: ChangeDetectionStrategy.Default
Without specifying changeDetection, Angular uses the default strategy automatically.
Angular
@Component({
  selector: 'app-sample',
  template: `<div>{{ count }}</div>`
})
export class SampleComponent {
  count = 0;
}
Sample Program

This component shows a number and a button. When you click the button, the number increases. The default change detection updates the view automatically to show the new number.

Angular
import { Component } from '@angular/core';

@Component({
  selector: 'app-counter',
  template: `
    <p>Count: {{ count }}</p>
    <button (click)="increment()">Increase</button>
  `
})
export class CounterComponent {
  count = 0;

  increment() {
    this.count++;
  }
}
OutputSuccess
Important Notes

The default strategy checks every component on each event, which is simple but can be slower for big apps.

You can improve performance by using ChangeDetectionStrategy.OnPush in advanced cases.

Summary

The default change detection strategy updates the view automatically when data changes.

It works well for most apps and is easy to use.

For better performance in big apps, consider other strategies.