A strong framework for creating dynamic web apps is Angular. One of its core features that ensures applications remain interactive and responsive is Angular Change Detection. This mechanism ensures that the view reflects updates in the application’s state. However, the default approach can sometimes lead to performance bottlenecks, especially in large applications. In this blog, we will explore different change detection strategies, including the popular OnPush strategy.
Angular Change Detection refers to the process by which the framework checks the component tree to see if any data has changed and updates the view accordingly. This process involves checking the component’s model or state, comparing it with the previous state, and if there are any changes, updating the DOM to reflect the new state.
Angular provides a default Angular Change Detection mechanism and also allows developers to customize this behavior using different strategies, the most commonly used being OnPush.
Angular offers two change detection strategies:
Let’s take a deeper look at both strategies:
By default, Angular uses ChangeDetectionStrategy.Default for all components. This strategy runs Angular Change Detection for all components in the application every time an event or action occurs that could potentially modify the application’s state. This includes user events, HTTP requests, timers, or subscriptions to observables.
How it Works:
🔹When an event occurs (such as a button click or HTTP response), Angular runs Angular Change Detection from the top of the component tree down to the affected component.
🔹It checks every component and updates the view if any bound properties have changed.
🔹This approach can be performance-intensive, especially for large applications with deep component trees or frequent state changes.
When to Use Default Strategy:
🔹Default Angular Change Detection is suitable for smaller applications or components where performance is not a concern.
🔹It is also useful when you want to ensure that the view is always in sync with the model, no matter how complex the state is.
Drawback:
🔹In large applications, frequent checks on all components can lead to performance issues as Angular Change Detection needs to perform checks on all components in the component tree.
Example:
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
changeDetection: ChangeDetectionStrategy.Default
})
export class ChildComponent {
@Input() data: any;
}
The OnPush strategy is an optimization technique that reduces the frequency of Angular Change Detection checks. When using OnPush, Angular will only check a component for changes if one of the following conditions is met:
With OnPush, Angular does not perform change detection on the component unless one of the above conditions is satisfied, reducing the overall change detection checks.
How it Works:
🔹OnPush triggers Angular Change Detection only when there’s a change in the component’s input properties, user-triggered events, or observable data.
🔹If none of these conditions occur, Angular will skip change detection for that component.
🔹This can lead to significant performance improvements, especially for large applications with immutable data and few updates to the component tree.
When to Use OnPush:
🔹OnPush is suitable for applications with immutable data or where most components don’t change their inputs frequently.
🔹It is beneficial for large applications or components that rely heavily on observables or do not require frequent updates.
Example:
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent {
@Input() data: any;
}
Advantages of OnPush:
🔹Reduced Performance Overhead: Since only components with new input properties or changes in observables are checked, the number of checks is greatly reduced.
🔹Faster Rendering: The application is more responsive because change detection is run less frequently.
Related read: Breaking Down Angular Change Detection System
While OnPush offers better performance, it may not always be the right choice depending on your application’s requirements. Let’s compare both strategies in different use cases:
Default Strategy is better suited when:
🔹Your application is simple, and performance is not a concern.
🔹You need to ensure that all components are always in sync with the data.
🔹The component tree is shallow, and change detection won’t cause a performance issue.
OnPush Strategy is better suited when:
🔹Your application is complex with many components.
🔹You are working with immutable data, and you want Angular to detect changes only when the inputs change.
🔹You are using observables and want Angular to run change detection only when the data changes.
🔹You want to optimize for performance by reducing unnecessary checks.
In some situations, you might need more control over when change detection occurs. Angular provides the ChangeDetectorRef service, which allows you to manually trigger change detection.
Methods of ChangeDetectorRef:
➡️ detectChanges(): Change detection for the present component and its offspring is manually triggered. This method forces Angular to check the component for changes even if it’s using OnPush strategy.
➡️ markForCheck(): Marks the current component for checking during the next change detection cycle. This is useful when you want Angular to check the component even if it’s using OnPush strategy but want to wait for the next cycle.
➡️ detach(): Detaches the change detector for the current component from the change detection tree. After detaching, Angular will no longer check the component for changes until it is reattached using reattach().
➡️ reattach(): Reattaches the change detector that was previously detached, allowing Angular to check the component again for changes.
These methods give you more fine-grained control over the change detection cycle and can help optimize performance or ensure that your component is updated in response to specific changes.
Example:
import { ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent {
constructor(private cdr: ChangeDetectorRef) {}
updateData(newData) {
this.data = newData;
this.cdr.markForCheck(); // Manually trigger change detection
}
}
Methods in Detail:
🔹detectChanges():
Forces change detection for the component and its children immediately. This method is useful when you need to update the view after a direct change in the component.
Example:
this.cdr.detectChanges();
🔹markForCheck():
Tells Angular to check the component in the next change detection cycle. This is especially useful when you have an OnPush strategy but still want Angular to perform change detection due to external factors like observables.
Example:
this.cdr.markForCheck();
🔹detach():
Detaches the component from the change detection tree. This stops Angular from checking the component for changes, which can be beneficial in certain scenarios like optimizing performance in large lists or complex components.
Example:
this.cdr.detach();
🔹reattach():
Reattaches the component to the change detection tree after it has been detached, so Angular can start checking it for changes again.
Example:
this.cdr.reattach();
Angular Change Detection strategies provide powerful tools for optimizing the performance of your application. The Default strategy is convenient and works for smaller applications, but it can cause performance issues in large applications. The OnPush strategy helps reduce unnecessary checks and improves performance, making it ideal for complex applications with immutable data.
By understanding and choosing the appropriate Angular Change Detection strategy based on your application’s needs, you can ensure that your Angular app is not only functional but also efficient and responsive.
The team at Mindbowser was highly professional, patient, and collaborative throughout our engagement. They struck the right balance between offering guidance and taking direction, which made the development process smooth. Although our project wasn’t related to healthcare, we clearly benefited...
Founder, Texas Ranch Security
Mindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork