Change Detection Strategies in Angular: Understanding Default
and OnPush
In Angular, change detection is the mechanism that allows the framework to track changes in component data and update the view accordingly. Understanding how this works and the strategies Angular offers can greatly improve the performance of your applications.
Let’s dive into the two main change detection strategies, Default
and OnPush
, and discuss their use cases with examples.
The Basics of Change Detection
Imagine your Angular application as a giant blackboard, and each component is a small section of that blackboard.
Now, every time someone changes something on their section of the blackboard, Angular needs to check if it needs to update the other sections too.
- Change Detection is like a teacher walking around the room, looking at each section of the blackboard, and updating it if needed.
- The teacher can be very attentive (checking every section all the time) or laid-back (only checking when explicitly told).
Angular provides two “attitudes” for the teacher:
- Default Change Detection — The teacher checks everything all the time.
- OnPush Change Detection — The teacher checks only specific things and only when explicitly told.
1. Default Change Detection Strategy
This is the default mode in Angular, and it’s like having a very active teacher checking everything. Whenever there’s a change anywhere in the component, Angular will run the change detection across the entire component tree, updating every component if needed.
Use Case: Simpler Applications or Applications with Frequent Data Changes
In applications where:
- Data is frequently changing (like real-time dashboards),
- You don’t want to manually manage when Angular should check for changes.
This approach ensures your components are always up-to-date with minimal effort.
@Component({
selector: 'app-dashboard',
template: `
<div>
<h1>{{ title }}</h1>
<button (click)="changeTitle()">Change Title</button>
</div>
`,
changeDetection: ChangeDetectionStrategy.Default
})
export class DashboardComponent {
title = 'Real-time Dashboard';
changeTitle() {
this.title = 'Updated Dashboard';
}
}
In this example, whenever you click the button, Angular will trigger a check for the entire component and its children, updating the view as necessary.
2. OnPush Change Detection Strategy
OnPush is like having a more laid-back teacher who only checks the blackboard when explicitly asked. Angular will only run change detection when:
- An input reference changes,
- An event is triggered inside the component (like a user click),
- Or manually triggered via
markForCheck
.
This is more efficient because it reduces the number of checks Angular has to perform, improving performance in large applications or applications with many components.
Use Case: Optimizing Performance in Large Applications
In scenarios where:
- Your application is large with many components,
- Data doesn’t change frequently (for example, static components that don’t update often),
- You want to manually control when Angular should check for changes (to improve performance).
@Component({
selector: 'app-profile',
template: `
<div>
<h1>{{ name }}</h1>
<button (click)="changeName()">Change Name</button>
</div>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProfileComponent {
@Input() name: string;
constructor(private cdRef: ChangeDetectorRef) {}
changeName() {
this.name = 'Updated Name';
// Manually triggering change detection
this.cdRef.markForCheck();
}
}
In this example, Angular won’t automatically check for changes in ProfileComponent
. Instead, you control when the view should be updated using markForCheck()
. If the name is updated from a parent component, Angular will detect that and update the view.
Choosing Between Default
and OnPush
- Use Default when your application is relatively small or when you want Angular to handle all the change detection automatically. It’s convenient and requires minimal effort from the developer.
- Use OnPush when you need performance optimization, especially in large applications or when components don’t change often. This strategy allows you to gain more control over when and how Angular updates the component views.
When Should You Use OnPush
?
- Static Data Display
When you’re working with components that display data that doesn’t change often, like a product listing or user profile,OnPush
is a great option because it avoids unnecessary checks, improving performance. - Optimizing Large Applications
In applications with hundreds of components, frequent change detection can slow things down. WithOnPush
, you can ensure that change detection only happens when necessary, reducing overhead. - Immutable Data
If your application uses immutable objects (where you always create new objects instead of modifying existing ones),OnPush
works well because Angular can easily detect when a new object is passed as an@Input()
and trigger an update accordingly.
Conclusion: The Right Strategy for Your Application
Choosing the right change detection strategy is essential for building efficient Angular applications.
- Default is great for simplicity, where the framework takes care of updating everything for you.
- OnPush gives you more control and performance optimization for larger or more complex applications.
In short, think of Default
as the strategy when you're okay with the framework doing all the work, and OnPush
as the strategy for more control and efficiency, especially when scaling your application.
Pro Tip: Start with Default
, and as your application grows, switch to OnPush
where performance becomes a concern!