Spread the love

In angular all components by default take the changes as any event occur, but sometime we don’t want this behaviour. Thus, to detach the two way binding in component we can use changeDetection strategy in component metadata. Angular Change Detection Strategy is simple to implement using the metadata of component.

There is two type of change detection strategies in angular.

  1. ChangeDetectionStrategy.Default
  2. ChangeDetectionStrategy.onPush

ChangeDetectionStrategy.Default

By default angular use ChangeDetectionStrategy.Default which means if you make changes in any variable, event, promises or XHR request then it will make all changes in your html file as well.

@Component({
  selector: "app-root",
  template: `
    <div>
      <h1>Counter: {{ this.inc }}</h1>
      <input
        type="button"
        (click)="this.update()"
        value="Update Counter"
      />
      <child-component></child-component>
    </div>
  `
})
export class AppComponent {
  inc = 0;

  update() {
    this.inc += 1;
  }
}



The above example will also update the child content.

ChangeDetectionStrategy.onPush

If we want more performance in our application or do not want dirty check on each event, XHR etc. then we can use ChangeDetectionStrategy.onPush. you basically tell angular to not guess anything on any event, it will only reflect the template if @Input decorator value changed or if developer wanted to make changes using the componentRef.markForChange() or changeDetectionRef.detectChanges() method.

@Component({
  selector: "app-root",
  template: `
    <div>
      <h1>Counter: {{ this.inc }}</h1>
      <input
        type="button"
        (click)="this.update()"
        value="Update Counter"
      />
      <child-component></child-component>
    </div>
  `,
changeDetection:ChangeDetectionStrategy.OnPush
})
export class AppComponent {
  inc = 0;

  update() {
    this.inc += 1;
  }
}



What is ChangeDetectionRef and how to use it?

ChangeDetectionRef is a base class which provides change detection functionality, when we called this ChangeDetectionRef.detectChanges() forcefully, it means detectChanges check the view and childrens and re-render the view even if the changeDetection strategy in component is ChangeDetectionStrategy.OnPush.

See the example below:

Leave a Reply