1️⃣ What does “change detection” mean?
Imagine your web page shows a person’s name:
If the variable name
changes from “Sam” to “Alex,” Angular needs to detect that change and update the screen.
The process of checking data and updating the HTML is called change detection.
2️⃣ Two main strategies in Angular
Angular gives you two modes to decide when it should check for changes:
🟢 Default (also called “CheckAlways”)
-
Angular will always look for changes in this component and all child components after almost any action:
-
Button clicks
-
HTTP responses
-
Timers (
setTimeout
,setInterval
) -
Browser events like scrolling
-
-
Easy to use because you don’t have to think about it.
-
But it can be slower if your app is very big, because Angular keeps checking everything many times.
🟡 OnPush
-
Angular will check the component only when one of these happens:
-
An
@Input()
value gets a new object reference.Important: if you just change a property inside the object, Angular will not notice. You must create a new object.
-
An event inside the component fires, like a button click.
-
You tell Angular to check manually using
ChangeDetectorRef.markForCheck()
.
-
-
This makes the app faster, because Angular skips unnecessary checks.
-
But you must follow an immutable data style (don’t mutate objects, create new ones).
3️⃣ Simple Example
Using Default
If you do:
✅ The screen updates automatically.
Using OnPush
If you do:
❌ The screen will NOT update, because the user
reference didn’t change.
✅ Correct way:
Now Angular sees a new object and updates the view.
4️⃣ When to Use Which
-
Default: Small or medium apps, or when you don’t want to worry about change detection rules.
-
OnPush: Large apps or performance-critical pages where you want to reduce unnecessary checks.
5️⃣ Manual Control (optional)
If you use OnPush and need to trigger a check yourself:
🏁 Summary
-
Default: Angular checks everything, every time → easier but heavier.
-
OnPush: Angular checks only on input reference change, internal event, or manual trigger → faster but needs immutable data handling.
This is the whole idea of Angular Change Detection Strategy in simple everyday English.
No comments:
Post a Comment