DEV Community

Cover image for Angular - Use ChangeDetectionStrategy.OnPush
Sandro Jhuliano Cagara
Sandro Jhuliano Cagara

Posted on

Angular - Use ChangeDetectionStrategy.OnPush

Angular gives us an option to choose the ChangeDetectionStrategy of a component. By default, the value is Default. It's recommended to change that to OnPush strategy to maximize the performance.

By default, Angular run its change detection cycle on all the components whenever there occurs some changes, like a simple click event or when we receive data from ajax calls. Running change detection cycle on every such events are costly and may affect the performance.

We can minimize these checks by setting our component's changeDetection to ChangeDetectionStrategy.OnPush. This will tell Angular to run change detection cycle only when:

  1. The Input reference changes.
  2. Some event occurs in the component or any of the children.
  selector: 'app-selector',
  changeDetection: ChangeDetectionStrategy.OnPush
Enter fullscreen mode Exit fullscreen mode

Note: Make use of detectChanges() or markForCheck() functions of ChangeDetectorRef to explicitely run the change detection cycle if required.

Resources: A Comprehensive Guide to Angular onPush Change Detection Strategy.

Thanks to @fyodorio .

Top comments (0)