DEV Community

Cover image for Change detections rules in angular
Islam Muhammad
Islam Muhammad

Posted on • Edited on

2

Change detections rules in angular

![alt](https://images.unsplash.com/reserve/81gZijLSWfge41LgzqQ6_Moving%20Parts.JPG?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1352&q=80) Photo by Chester Alvarez on Unsplash

What makes angular running change detection and how to optimize it

What is change detection?

Change detection is the mechanism designed to track changes in an application state and render the updated state on the screen. It ensures that the user interface always stays in sync with the internal state of the program.

How change detections work in angular?

Angular uses ZoneJS to intercept events that occurred in the application and run a change detection cycle automatically.

We can reduce events that angular intercept by changing ChangeDetectionStrategy in component decorator to ChangeDetectionStrategy.OnPush

ChangeDetectionStrategy.OnPush tells Angular that the component only depends on its @inputs() ( aka pure ) and needs to be checked only in the following cases:

1️⃣ The Input reference changes.
2️⃣ An event originated from the component or one of its children. ( The rule applies only to DOM events)
3️⃣ We run change detection explicitly.
4️⃣ Observable emits a new value inside the component template.

How to optimize running of change detection

  • Always use OnPush Change Detection Strategy.
  • Always use immutable data because once you set component to OnPush strategy angular will use shallow comparison to detect change and perform the reRender task.
  • Prevent unnecessary emits in observables inside component.
  • Prevent triggers unnecessary async task like scrolling using technics like Debounce or Throttle.
  • Reduce the number of long tasks by moving it to Web Workers.
  • Use runOutsideAngular when starting a work consisting of one or more asynchronous tasks that don't require UI.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

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