DEV Community

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

Posted on

3

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.
@Component({
  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 .

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay