Reader small image

You're reading from  Angular Cookbook - Second Edition

Product typeBook
Published inDec 2023
Reading LevelBeginner
PublisherPackt
ISBN-139781803233444
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Muhammad Ahsan Ayaz
Muhammad Ahsan Ayaz
author image
Muhammad Ahsan Ayaz

Muhammad Ahsan Ayaz is a Google developers expert in Angular, a software architect, and a head instructor of JavaScript at the School of Applied Technology. He loves helping the start-up ecosystem and product owners to bring their ideas to life using JavaScript, Angular, and web technologies. He has built several open-source projects that he maintains and he speaks at events, along with creating articles and video courses.
Read more about Muhammad Ahsan Ayaz

Right arrow

Performance Optimization in Angular

Performance is always a concern in any product that you build for end users. It is a critical element in increasing the chances of someone using your app for the first time becoming a customer. Now, we can’t really improve an app’s performance until we identify potential possibilities for improvement and the methods to achieve this. In this chapter, you’ll learn some methods to deploy when it comes to improving Angular applications. You’ll learn how to analyze, optimize, and improve your Angular app’s performance using several techniques. Here are the recipes we’re going to cover in this chapter:

  • Using OnPush change detection to prune component subtrees
  • Detaching the change detector from components
  • Running async events outside Angular with runOutsideAngular
  • Using trackBy for lists with *ngFor
  • Moving heavy computation to pure pipes
  • Using web workers for heavy computation...

Technical requirements

For the recipes in this chapter, ensure your setup is complete as per the 'Technical Requirements' in the 'Angular-Cookbook-2E' GitHub repository. For setup details, visit: https://github.com/PacktPublishing/Angular-Cookbook-2E/tree/main/docs/technical-requirements.md. The starter code for this chapter is located at https://github.com/PacktPublishing/Angular-Cookbook-2E/tree/main/start/apps/chapter12.

Using OnPush change detection to prune component subtrees

In today’s world of modern web applications, performance is one of the key factors for a great User Experience (UX) and, ultimately, conversions for a business. In this recipe, the first recipe of this chapter, we’re going to discuss the fundamental or the most basic optimization you can do with your components wherever it seems appropriate, which is by using the OnPush change detection strategy. The app we’re working with has some performance issues, particularly with the UserCardComponent class. This is because it uses a getter function, randomColor, to generate a random color for its background. Behind the scenes, that function uses a factorial function to add more processing time. But that is just to demonstrate a component that can cause the UI to hang if there is some complex calculation happening, along with multiple change detections being triggered.

Getting ready

The app that we are going...

Detaching the change detector from components

In the previous recipe, we learned how to use the OnPush strategy in our components to avoid Angular change detection running unless one of the @Input() bindings has changed. There is, however, another way to tell Angular to not run change detection at all for a particular component and its subtree. This cuts the component and its subtree from the change detection cycle completely, as shown in Figure 12.5, which can result in an increase in the overall performance. This is also handy when you want full control of when to run change detection. In this recipe, you’ll learn how to completely detach the change detector from an Angular component to gain performance improvements.

Figure 12.5: Change detector detached from component tree

Getting ready

The app that we are going to work with resides in start/apps/chapter12/ng-cd-ref inside the cloned repository:

  1. Open the code repository in your code editor.
  2. ...

Running async events outside Angular with runOutsideAngular

Angular runs its change detection mechanism on a couple of things, including—but not limited to—all browser events, such as keyup, keydown, click, and so on. It also runs change detection on setTimeout, setInterval, and Ajax HTTP calls. If we had to avoid running change detection on any of these events, we’d have to tell Angular not to trigger change detection on them—for example, if you use the setInterval method in your Angular component, it will trigger an Angular change detection cycle each time its callback method is called. This can lead to a huge amount of change detection cycles and your app might even hang. An ideal situation would be to be able to still use the setInterval method and so on without triggering the change detection. In this recipe, you’ll learn how to do exactly that. You will learn how to execute code blocks outside of zone.js using the NgZone service, particularly...

Using trackBy for lists with *ngFor

Lists are an essential part of most of the apps we build today. If you’re building an Angular app, there’s a great chance you will use the *ngFor directive at some point for rendering lists. The *ngFor directive allows us to loop over arrays or objects generating HTML for each item. However, if we are rendering large lists, using *ngFor without caution may cause performance issues, especially when the source for *ngFor is changed completely (the entire array is replaced). In this recipe, we’ll learn how we can improve the performance of lists using the *ngFor directive with the trackBy function. Let’s get started.

Getting ready

The app that we are going to work with resides in start/apps/chapter12/ng-for-trackby inside the cloned repository:

  1. Open the code repository in your code editor.
  2. Open the terminal, navigate to the code repository directory, and run the following command to serve the project...

Moving heavy computation to pure pipes

In Angular, we have a particular way of writing components. Since Angular is heavily opinionated, we already have a lot of guidelines from the community and the Angular team on what to consider when writing components—for example, making HTTP calls directly from a component is considered a not-so-good practice. Similarly, if we have heavy computation in a component that triggers with each change detection cycle, this is also not considered a good practice. Imagine that the view depends upon a transformed version of the data using a computation constantly. This would cause a lot of computation and processing for each render cycle. One good technique can be to move the heavy computation using Angular (pure) pipes (especially if the computation happens with each change detection cycle).

Getting ready

The app that we are going to work with resides in start/apps/chapter12/ng-pipes-perf inside the cloned repository:

  1. Open the...

Using web workers for heavy computation

If your Angular application does a lot of computation during an action, there’s a high chance that it will block the UI thread. This will cause a lag in rendering the UI because it blocks the main JavaScript thread. Web workers allow us to run heavy computation in the background thread, thus freeing the UI thread as it is not blocked. In this recipe, we’re going to use an application that does a heavy computation in the UserService class. It creates a unique ID for each user card and saves it into localStorage. However, it loops a couple of thousand times before doing so, which causes our application to hang for a while. In this recipe, we’ll move the heavy computation from the components to a web worker and will also add a fallback in case web workers aren’t available.

Getting ready

The app that we are going to work with resides in start/apps/chapter12/ng-ww-perf inside the cloned repository:

  1. Open...

Using performance budgets for auditing

In today’s world, most of the population has a good internet connection to use everyday applications, be it a mobile app or a web app, and it is fascinating how much data we ship to our end users as a business. The amount of JavaScript shipped to users has an ever-increasing trend now, and if you’re working on a web app, you might want to use performance budgets to make sure the bundle size doesn’t exceed a certain limit. With Angular apps, setting the budget sizes is a breeze. In this recipe, you’re going to learn how to use the performance budgets to ensure small bundle sizes for our Angular apps.

Getting ready

The app that we are going to work with resides in start/apps/chapter12/ng-perf-budgets inside the cloned repository:

  1. Open the code repository in your code editor.
  2. Open the terminal, navigate to the code repository directory, and run the following command to build the project: ...

Analyzing bundles with webpack-bundle-analyzer

In the previous recipe, we looked at configuring budgets for our Angular app, and this is useful because you get to know when the overall bundle size exceeds a certain threshold, although you don’t get to know how much each part of the code contributes to the final bundles. This is what we call analyzing the bundles, and in this recipe, you will learn how to use webpack-bundle-analyzer to audit the bundle sizes and the factors contributing to them.

Getting ready

The app that we are going to work with resides in start/apps/chapter12/ng-perf-wba inside the cloned repository:

  1. Open the code repository in your code editor.
  2. Open the terminal, navigate to the code repository directory, and run the following command to build the project:
    npm run build ng-perf-wba
    

    This should build the app, and you should see the following in the terminal:

    Figure 12.33: The ng-perf-wba app running at...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Angular Cookbook - Second Edition
Published in: Dec 2023Publisher: PacktISBN-13: 9781803233444
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Muhammad Ahsan Ayaz

Muhammad Ahsan Ayaz is a Google developers expert in Angular, a software architect, and a head instructor of JavaScript at the School of Applied Technology. He loves helping the start-up ecosystem and product owners to bring their ideas to life using JavaScript, Angular, and web technologies. He has built several open-source projects that he maintains and he speaks at events, along with creating articles and video courses.
Read more about Muhammad Ahsan Ayaz