Monday, 22 September 2025

change detection

1️⃣ What does “change detection” mean?

Imagine your web page shows a person’s name:

<p>{{name}}</p>

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:

    1. 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.

    2. An event inside the component fires, like a button click.

    3. 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

@Component({ selector: 'app-user', template: `<p>{{user.name}}</p>` }) export class UserComponent { @Input() user!: { name: string }; }

If you do:

this.user.name = 'Alex';

✅ The screen updates automatically.


Using OnPush

@Component({ selector: 'app-user', template: `<p>{{user.name}}</p>`, changeDetection: ChangeDetectionStrategy.OnPush }) export class UserComponent { @Input() user!: { name: string }; }

If you do:

this.user.name = 'Alex';

❌ The screen will NOT update, because the user reference didn’t change.

✅ Correct way:

this.user = { ...this.user, name: 'Alex' };

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:

constructor(private cd: ChangeDetectorRef) {} someAsyncWork() { // after getting new data this.cd.markForCheck(); // tell Angular to re-check this component }

🏁 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