Bird
Raised Fist0
Angularframework~15 mins

OnPush change detection strategy in Angular - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - OnPush change detection strategy
What is it?
OnPush change detection strategy is a way Angular decides when to update a component's view. Instead of checking for changes all the time, it only checks when specific inputs change or events happen. This makes apps faster by reducing unnecessary work. It is a setting you apply to components to control how Angular tracks changes.
Why it matters
Without OnPush, Angular checks every component on every event, which can slow down apps as they grow. OnPush helps apps run smoothly by only updating when really needed. This saves battery on phones and makes websites feel quicker. It solves the problem of wasted work and lag in user interfaces.
Where it fits
Before learning OnPush, you should understand Angular components, data binding, and the default change detection process. After mastering OnPush, you can explore advanced state management and performance optimization techniques in Angular.
Mental Model
Core Idea
OnPush tells Angular to check a component only when its inputs change or an event inside it happens, skipping unnecessary checks.
Think of it like...
Imagine a security guard who only checks a room when someone rings the doorbell or brings a package, instead of checking every room all the time.
┌─────────────────────────────┐
│ Angular Component            │
│                             │
│  Inputs changed? ──► Check view update
│  Event inside? ──────► Check view update
│  Otherwise ──────────► Skip check
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Angular Change Detection
🤔
Concept: Angular automatically updates the screen when data changes using a process called change detection.
Angular runs change detection after events like clicks or HTTP responses. It checks all components to see if their data changed and updates the view accordingly.
Result
The screen always shows the latest data but Angular may do more work than needed.
Understanding the default change detection is key to seeing why OnPush can improve performance.
2
FoundationWhat Triggers Default Change Detection
🤔
Concept: Default change detection runs after many events, including user actions and timers.
Every time something happens, Angular checks every component from top to bottom to see if it needs to update the view.
Result
Even components with no changes get checked, which can slow down big apps.
Knowing what triggers checks helps understand how OnPush reduces unnecessary work.
3
IntermediateHow OnPush Changes Detection Behavior
🤔Before reading on: Do you think OnPush checks components more often, less often, or the same as default? Commit to your answer.
Concept: OnPush tells Angular to check a component only when its input properties change or an event happens inside it.
When a component uses OnPush, Angular skips checking it unless: - An input property changes by reference - An event originated inside the component - You manually trigger change detection This reduces the number of checks Angular performs.
Result
Components with OnPush update less often, improving app speed.
Understanding OnPush's selective checking is crucial for optimizing Angular apps.
4
IntermediateInput Property Change Detection with OnPush
🤔Before reading on: Does OnPush detect changes if an input object's internal data changes but its reference stays the same? Commit to your answer.
Concept: OnPush relies on input property references changing, not internal mutations.
If an input is an object and you change a property inside it without changing the object itself, OnPush will NOT detect this change. You must replace the object with a new one to trigger detection.
Result
Only new object references cause OnPush to update the component view.
Knowing this prevents bugs where UI doesn't update because of mutable data changes.
5
IntermediateEvents and Manual Triggers with OnPush
🤔
Concept: OnPush also updates when events happen inside the component or when manually triggered.
User actions like clicks inside the component trigger change detection even if inputs don't change. Developers can also call methods like markForCheck() to force updates.
Result
OnPush components stay responsive to user interaction and manual updates.
Recognizing these triggers helps balance performance with UI responsiveness.
6
AdvancedCombining OnPush with Immutable Data Patterns
🤔Before reading on: Do you think using mutable or immutable data works better with OnPush? Commit to your answer.
Concept: OnPush works best with immutable data, where new objects replace old ones instead of changing them.
Immutable data means every change creates a new object. This fits OnPush's need for new references to detect changes. Libraries like NgRx use this pattern to optimize Angular apps.
Result
Using immutable data with OnPush leads to predictable and efficient UI updates.
Understanding this synergy is key to mastering Angular performance.
7
ExpertCommon Pitfalls and Debugging OnPush Components
🤔Before reading on: Can OnPush cause a component to not update even when data changes? Commit to your answer.
Concept: OnPush can cause UI not to update if data changes are not done by replacing references or if change detection is not triggered properly.
Developers often forget to replace objects or call detectChanges(). This leads to stale views. Debugging requires checking input references and event triggers carefully.
Result
Knowing these pitfalls helps avoid subtle bugs and improves app reliability.
Recognizing OnPush's limits prevents frustrating UI bugs in production.
Under the Hood
Angular uses a tree of components and runs change detection by traversing this tree. With OnPush, Angular marks components as 'check only if inputs changed or events fired'. It compares input references using strict equality. If unchanged, Angular skips checking that component's template. This reduces CPU cycles and DOM updates.
Why designed this way?
OnPush was designed to improve performance by avoiding unnecessary checks in large apps. The default strategy is simple but inefficient for big component trees. OnPush leverages immutable data patterns and event-driven updates to minimize work while keeping UI consistent.
┌───────────────┐       ┌───────────────┐
│ Parent Comp   │──────▶│ Child Comp    │
│ (Default)     │       │ (OnPush)      │
└───────────────┘       └───────────────┘
       │                      │
       │ Input reference changed?
       │ Yes ──────────────▶ Check and update
       │ No ───────────────▶ Skip check
       │ Event inside comp?
       │ Yes ──────────────▶ Check and update
       │ No ───────────────▶ Skip check
Myth Busters - 4 Common Misconceptions
Quick: Does OnPush detect changes when you modify a property inside an input object without changing its reference? Commit to yes or no.
Common Belief:OnPush detects all changes inside input objects automatically.
Tap to reveal reality
Reality:OnPush only detects changes if the input object's reference changes, not internal mutations.
Why it matters:Believing this causes bugs where the UI does not update because Angular thinks nothing changed.
Quick: Does OnPush mean Angular never checks the component again after first render? Commit to yes or no.
Common Belief:OnPush disables change detection completely for the component.
Tap to reveal reality
Reality:OnPush only limits checks to specific triggers; events and manual calls still cause updates.
Why it matters:Thinking OnPush disables updates leads to confusion and broken UI.
Quick: Is OnPush always faster than default change detection? Commit to yes or no.
Common Belief:OnPush always improves performance no matter what.
Tap to reveal reality
Reality:OnPush can add complexity and overhead if used incorrectly or with mutable data.
Why it matters:Misusing OnPush can cause worse performance and harder debugging.
Quick: Can OnPush cause a component to update even if inputs don't change? Commit to yes or no.
Common Belief:OnPush only updates when inputs change.
Tap to reveal reality
Reality:Events inside the component or manual triggers can also cause updates with OnPush.
Why it matters:Ignoring event triggers leads to misunderstanding component behavior.
Expert Zone
1
OnPush works best with immutable data but can be combined with manual change detection calls for mutable data scenarios.
2
Angular's internal change detection uses a 'dirty checking' mechanism that OnPush optimizes by skipping subtrees, but this requires careful input management.
3
Using OnPush with async pipes and observables can further optimize performance by reducing manual change detection triggers.
When NOT to use
Avoid OnPush if your app heavily relies on mutable shared state without immutable patterns or if you cannot guarantee input reference changes. In such cases, default change detection or manual change detection control might be better.
Production Patterns
In real apps, OnPush is combined with state management libraries like NgRx or Akita that enforce immutability. Developers use OnPush to optimize large component trees and rely on async pipes to handle observable data streams efficiently.
Connections
Immutable Data Structures
OnPush builds on the idea of immutable data to detect changes efficiently.
Understanding immutable data helps grasp why OnPush relies on reference changes to trigger updates.
Event-Driven Programming
OnPush triggers updates on internal events, linking it to event-driven design.
Knowing event-driven principles clarifies how user actions cause UI updates even with OnPush.
Selective Rendering in Video Games
Both OnPush and selective rendering optimize performance by updating only changed parts.
Recognizing this cross-domain pattern shows how efficient updates improve user experience in different fields.
Common Pitfalls
#1UI does not update after changing a property inside an input object.
Wrong approach:this.inputObject.property = newValue; // OnPush component does not update
Correct approach:this.inputObject = {...this.inputObject, property: newValue}; // New reference triggers update
Root cause:Misunderstanding that OnPush detects changes by object reference, not internal mutations.
#2Expecting OnPush component to update without any input or event changes.
Wrong approach:No input changes or events, but expecting UI refresh automatically.
Correct approach:Call ChangeDetectorRef.markForCheck() or detectChanges() to manually trigger update.
Root cause:Not realizing OnPush limits automatic checks to specific triggers.
#3Using OnPush without immutable data leads to stale UI.
Wrong approach:Mutating shared objects passed as inputs without changing references.
Correct approach:Use immutable patterns or replace objects to ensure OnPush detects changes.
Root cause:Ignoring the need for new references with OnPush strategy.
Key Takeaways
OnPush change detection improves Angular app performance by checking components only when inputs change or events occur.
It relies on input property references changing, so immutable data patterns work best with OnPush.
Events inside the component and manual triggers also cause OnPush components to update.
Misusing OnPush by mutating objects without changing references causes UI bugs.
Understanding OnPush helps build faster, more efficient Angular applications.

Practice

(1/5)
1. What does the OnPush change detection strategy do in Angular?
easy
A. It disables change detection completely.
B. It checks for changes only when input properties change or events occur.
C. It forces Angular to check for changes on every event regardless of inputs.
D. It updates the component only when manually triggered by the developer.

Solution

  1. Step 1: Understand OnPush behavior

    OnPush strategy tells Angular to run change detection only when input properties change or events happen inside the component.
  2. Step 2: Compare with other options

    Options A, C, and D describe behaviors that are not how OnPush works. It does not disable detection, nor does it check on every event or require manual triggers.
  3. Final Answer:

    It checks for changes only when input properties change or events occur. -> Option B
  4. Quick Check:

    OnPush triggers on input or event changes = B [OK]
Hint: OnPush triggers only on input or event changes [OK]
Common Mistakes:
  • Thinking OnPush disables change detection
  • Believing OnPush checks on every event
  • Assuming manual triggers are required
2. Which is the correct way to set the OnPush change detection strategy in an Angular component?
easy
A. @Component({ selector: 'app', changeDetection: ChangeDetectionStrategy.OnPush })
B. @Component({ selector: 'app', changeDetection: ChangeDetectionStrategy.Default })
C. @Component({ selector: 'app', changeDetection: 'OnPush' })
D. @Component({ selector: 'app', changeDetectionStrategy: OnPush })

Solution

  1. Step 1: Recall Angular syntax for change detection

    The correct property name is changeDetection and the value is ChangeDetectionStrategy.OnPush.
  2. Step 2: Analyze options

    @Component({ selector: 'app', changeDetection: ChangeDetectionStrategy.OnPush }) uses the correct property and enum value. @Component({ selector: 'app', changeDetection: ChangeDetectionStrategy.Default }) uses Default strategy, C uses a string instead of enum, and D uses a wrong property name.
  3. Final Answer:

    @Component({ selector: 'app', changeDetection: ChangeDetectionStrategy.OnPush }) -> Option A
  4. Quick Check:

    Use changeDetection with enum OnPush = A [OK]
Hint: Use changeDetection: ChangeDetectionStrategy.OnPush exactly [OK]
Common Mistakes:
  • Using string 'OnPush' instead of enum
  • Wrong property name like changeDetectionStrategy
  • Confusing Default with OnPush
3. Given this Angular component with OnPush strategy:
@Component({
  selector: 'counter',
  template: `{{count}}`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CounterComponent {
  @Input() count = 0;
}

If the parent updates count from 0 to 1, what will happen?
medium
A. The component updates only if an event inside it triggers change detection.
B. The component view does not update until manually triggered.
C. The component view updates to show 1 immediately.
D. The component throws an error because OnPush disallows input changes.

Solution

  1. Step 1: Understand OnPush input update behavior

    OnPush triggers change detection when input properties change, so updating count from parent triggers view update.
  2. Step 2: Evaluate other options

    The component view does not update until manually triggered. is wrong because manual trigger is not needed for input changes. The component throws an error because OnPush disallows input changes. is false; OnPush allows input changes. The component updates only if an event inside it triggers change detection. is incomplete because input changes alone trigger detection.
  3. Final Answer:

    The component view updates to show 1 immediately. -> Option C
  4. Quick Check:

    Input change triggers OnPush update = D [OK]
Hint: Input changes trigger OnPush updates automatically [OK]
Common Mistakes:
  • Thinking manual detection is needed for input changes
  • Believing OnPush blocks input updates
  • Confusing event triggers with input triggers
4. You have an Angular component using OnPush strategy. Inside it, you update a local variable without changing any input. The view does not update. What is the likely cause?
medium
A. The component must use Default strategy to update local variables.
B. OnPush disables all change detection, so no updates happen.
C. You must call detectChanges() manually for every change.
D. OnPush only checks for input changes or events, so local changes don't trigger detection.

Solution

  1. Step 1: Recall OnPush detection triggers

    OnPush triggers change detection only on input changes or events inside the component.
  2. Step 2: Understand local variable update effect

    Updating a local variable without input change or event does not trigger detection, so view stays the same.
  3. Step 3: Analyze other options

    OnPush disables all change detection, so no updates happen. is false; OnPush does not disable detection completely. You must call detectChanges() manually for every change. is sometimes needed but not always. The component must use Default strategy to update local variables. is incorrect; Default strategy is not required for local updates.
  4. Final Answer:

    OnPush only checks for input changes or events, so local changes don't trigger detection. -> Option D
  5. Quick Check:

    Local changes need input/event to trigger OnPush = A [OK]
Hint: OnPush ignores local changes without input or event triggers [OK]
Common Mistakes:
  • Assuming OnPush disables all detection
  • Forgetting to trigger detection manually when needed
  • Thinking Default strategy is required for local updates
5. You have a parent component passing an object as input to a child component using OnPush strategy. The parent updates a property inside the object without changing the object reference. Will the child detect the change and update its view?
hard
A. No, because OnPush only detects changes when the input reference changes.
B. Yes, but only if you call markForCheck() manually.
C. Yes, because OnPush detects deep changes inside objects automatically.
D. No, because OnPush disables all change detection for objects.

Solution

  1. Step 1: Understand OnPush input change detection

    OnPush detects changes by checking if the input reference changes, not deep object mutations.
  2. Step 2: Analyze object mutation effect

    Changing a property inside the object without changing the reference does not trigger OnPush detection.
  3. Step 3: Evaluate other options

    Yes, because OnPush detects deep changes inside objects automatically. is false because OnPush does not do deep checks. Yes, but only if you call markForCheck() manually. is partially true but not automatic. No, because OnPush disables all change detection for objects. is incorrect; OnPush does not disable detection for objects.
  4. Final Answer:

    No, because OnPush only detects changes when the input reference changes. -> Option A
  5. Quick Check:

    OnPush detects input reference changes only = C [OK]
Hint: OnPush tracks input references, not deep object changes [OK]
Common Mistakes:
  • Assuming deep object changes trigger OnPush
  • Thinking OnPush disables detection for objects
  • Forgetting to update object reference to trigger detection