Angular's change detection mechanism is one of the core features that keeps the application’s view (DOM) in sync with its underlying data model. It determines what changed and updates the view accordingly. Let’s dive into how it works under the hood, and how it has evolved—especially with Ivy.
🔄 How Angular Change Detection Works
📌 1. The Core Idea
Angular uses a unidirectional data flow and a tree of components. Each time an event occurs (like a user input or a timer), Angular performs change detection to check if any data-bound properties in the component tree have changed—and updates the DOM accordingly.
🧠 Under the Hood: The Process
Step-by-step Overview:
-
Triggering Change Detection
Angular’s change detection is triggered by:-
Browser events (
click
,input
, etc.) -
Timers (
setTimeout
,setInterval
) -
HTTP responses
-
Manual triggers (
ChangeDetectorRef.detectChanges()
)
This is usually wrapped by
NgZone
, which patches async APIs to automatically trigger a re-evaluation when the JS stack is clear. -
-
Component Tree Traversal
Angular starts from the root component and traverses down the component tree, checking each component for data changes. -
Template Expressions Re-evaluated
For each component:-
Angular re-evaluates the bindings in the template (like
{{title}}
,[src]
, etc.). -
If a new value is different from the previous one (using strict identity comparison
===
), the DOM is updated.
-
-
View Update
The DOM is updated only if necessary, based on the latest data vs. previous values.
🧱 Change Detection Strategies
🔁 1. Default
-
Angular checks every component on every change detection cycle.
-
Good for simplicity, but can be inefficient in large apps.
🧩 2. OnPush
-
Angular checks a component only if:
-
An @Input() reference has changed.
-
You call
markForCheck()
manually.
-
-
Great for performance in well-structured apps.
🌿 Ivy vs. View Engine in Change Detection
With Ivy:
-
Change detection is more granular and efficient.
-
Ivy uses template instructions (like
Δɵtext
,Δɵelement
) during compilation to optimize DOM updates. -
It does per-component change detection, reducing unnecessary checks.
🛠️ Optimizations You Can Do
-
Use
OnPush
change detection in performance-critical components. -
Avoid mutating objects/arrays directly—use new references so Angular can detect changes.
-
Detach change detection with
ChangeDetectorRef.detach()
for parts of the UI that rarely change. -
Use
trackBy
in*ngFor
to prevent unnecessary DOM manipulation.
📊 Visual Summary
Angular Change Detection Flow:
✅ Final Thoughts
Angular’s change detection is powerful and efficient—especially with Ivy. It minimizes manual DOM manipulation and keeps your view in sync with your data model. Understanding how it works lets you make smarter decisions for performance and architecture.