Skip to content

Change detection rules in angular

Published: at 12:00 AM

⏰ 2 min read

change Photo by Ross Findon 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