In modern web development, performance is crucial for delivering responsive and efficient applications. Angular, as a powerful framework, offers various features and optimizations to enhance performance. This blog post outlines best practices to ensure your Angular applications run smoothly and efficiently.
ChangeDetectionStrategy.onPush Strategy
For better performance, it’s recommended to use ChangeDetectionStrategy.onPush for all components unless a specific component requires the default strategy.
The default strategy forces Angular to rerun change detection on all components that exist on the page, even if a user interaction only changes one variable in a small component. Usually, Angular runs change detection on every user interaction with the page (click, scroll, focus, input) and it might not be an issue for small applications but becomes a problem when an application becomes larger. As the application grows, each change detection cycle takes more time, leading to sluggishness and potential freezes.
When using ChangeDetectionStrategy.onPush, Angular is instructed to only run change detection on that component in specific scenarios, but only run this check and do component rerender on a restricted, smaller amount of rules:
- When component Input() properties change
- When a new value is propagated into a stream which is used in a template with an | async pipe
- When a user interacts with elements that are defined inside this component
- When child components emit an event and this parent component is subscribed to it
- If you manually trigger change detection using
ChangeDetectorRef.detectChanges()orChangeDetectorRef.markForCheck().
Although it restricts the developer about how the code should be written in the app, in the long term it should significantly improve application performance and speed up application response to user actions.
Avoid Heavy Functions in Templates (Except Event Handlers)
During each rerender cycle angular checks the template properties, and rerenders the view if those properties have changed. Using functions (especially heavy ones) for assigning some property in template would force angular to run that function in EACH rerender cycle (that might happen even 5-10 times per second). That makes any user interaction with an app really slow.
Suggestion: Cache the function result into a component property and use that instead
Bad example:
<div [class.some-class]=”someHeavyFunction()”>{{anotherHeavyFunction()}}</div>
Good example:
<div [class.some-class]=”someProp”>{{anotherProp}}</div>
Lazy Load Pages or Modules
The main thing that affects the initial app load time in Angular is the core bundle size (main.js). The best way to significantly improve the loading time – to split up the application on the independent lazy loaded modules for each page.
Lazy loading some heavy pages or libraries would significantly reduce the main bundle size and improve the first app load speed
Data Lazy Loading / Lazy Rendering
Rendering a large amount of data on the page might cause a freeze that is visible to a user. Using lazy loading/rendering for large data sets (lists, tables, etc…) that should be displayed on the page should resolve that issue. In general, the rule is: render only a small part of data that would fit into one-two screens and then lazy load or lazy render the rest part of data while a user scrolls or paginates to the next page.
So there are few rules and techniques that we should consider during development:
- Lazy load / lazy render data while scrolling a list or a table
- Render popup and its data only when a user clicks on it (exceptions are: small tooltips, small popups with static data)
Browser Events Handling
Usually browser events (scroll for example) generate a lot of events during one second (10-100). For development purposes we usually don’t need all of them, so it might be useful to limit them by using following rxjs operators: debounceTime, auditTime, throttleTime.
Note: Handling of any browser event in the app would also trigger angular change detection cycle that might cause performance issues described in `ChangeDetectionStrategy.onPush strategy` section above. So limiting them would have a positive effect on the application performance in general.
Use `pure` Flag for Pipes
This flag indicates that the pipe is pure, which means that Angular executes the pipe only when it detects a pure change to the input value. It allows angular to cache results and to skip redundant calculations on each change detection run, if input params for a pipe were not changed.
Conclusion
Prioritizing performance in Angular applications is essential to delivering a superior user experience. By following best practices such as optimizing change detection, leveraging lazy loading, and managing event handlers and subscriptions efficiently, developers can build responsive and efficient applications. Regular performance monitoring and staying up to date with Angular’s latest features further enhance performance.
Implementing these guidelines will help ensure that your Angular applications not only meet user expectations but also stand out in a competitive landscape.
If you’re experiencing performance issues in your Angular applications or have custom software needs, don’t hesitate to contact Trailhead. Our expert team is here to help you optimize your applications and achieve your business goals.