DEV Community

Cover image for Best Practices for Angular Performance Optimization
Eric Walter
Eric Walter

Posted on

Best Practices for Angular Performance Optimization

While creating scalable web applications their performance is a top priority for web developers. Slow applications not only irritate users but also negatively impact brand reputation. That’s why modern web development frameworks like Angular need to maximize the performance of web apps. I am writing this blog to explain all the best practices for Angular performance optimization that you can adopt right away to maximize your app speed.

What is Angular Performance Optimization?

Performance optimization in Angular comprises a set of strategies and techniques to improve the overall speed, responsiveness, and user experience of an Angular application. Moreover, it includes better change detection, minimizing load times, and reducing the size of the final bundle.

Some Best Practices to Boost Angular Apps’ Speed

Some best techniques for boosting Angular apps’ speed include:

1. Lazy Loading Modules

To improve Angular performance Lazy loading is one of the most powerful strategies. This way, you can only concentrate and load those parts of applications that users interact with rather than loading everything.

For instance, you can asynchronously load a module when the user interacts with it. You can deploy lazy loading by following this command:

const routes: Routes = [ 

  {

    path: ‘feature’, 

    loadChildren: () => import(‘./feature/feature.module’). then (m => m.FeatureModule )

  }

];
Enter fullscreen mode Exit fullscreen mode

If you find it hectic to manage you can hire Angular developers to ensure lazy loading to improve Angular app performance.

2. Optimizing Change Detection Mechanism

If your Angular change detection mechanism is not properly handled it can cause performance issues. Angular uses CheckAlways detection technique to check the whole component tree to point out any change in an event. If you want to optimize this, you can opt for the OnPush change detection technique for pointing out any change only with the change of input properties of the component.

@Component ({ 

  Selector: ‘app-user’,

  changeDetection: ChangeDetectionStrategy. OnPush,

  templateUrl: ‘./user.component. html’,

})

export class UserComponent {

  @Input () user: User;

}
Enter fullscreen mode Exit fullscreen mode

Moreover, it helps in minimizing the number of unnecessary checks.

3. Optimize ngFor Through Track By

For navigating any recently changed item in the list you can use trackby function. You can optimize ngFor with trackby:

html 

<div *ngFor= “let item of items;  trackBy:  trackById”> 

  {{ item.name }} 

</div>
Enter fullscreen mode Exit fullscreen mode

With the help of the Track by Id function:

trackById (index: number, item: any): number { 

  return item. Id; 

}
Enter fullscreen mode Exit fullscreen mode

This Angular optimization technique would assist in tracking each item with its distinct identifier.

4. Reduce Bundle Size with AOT and Tree Shaking

Size of the application bundle can be reduced by the built-in Angular mechanism responsible for better Angular performance. One of these built-in systems is Ahead of Time Compilation (AOT). Moreover, Angular applications become faster to load and smaller because AOT compiles templates and components during the build process.

AOT can be enabled through this command:

ng build  --aot
Enter fullscreen mode Exit fullscreen mode

Moreover, the tree-shaking technique can be utilized for reducing the size of third-party libraries removing unused code from the final bundle.

5. Utilize Pure Pipes and Avoid Impure ones

In Angular, data can be transferred into templates through pipes. However, if these get impure that would be a bottleneck in your app performance. That’s why it's important to avoid impure pipes.
If you want to identify an impure pipe, it might look like this:

@Pipe ({ 

  name: ‘expensivePipe’ , 

  Pure: false 

}) 

export class ExpensivePipe implements PipeTransform { 

  transform (value: any): any { 

    // expensive operation 

  }

}
Enter fullscreen mode Exit fullscreen mode

Also, especially in large applications it is important to shift from impure pipes to pure ones.

6.Heavy Computation Through Web Workers

For heavy computation tasks, work can be offloaded to web workers. With a Web Worker it becomes possible to run scripts in background thread.

I am giving a simple example below of utilizing a Web Worker:

const worker = new Worker(‘./worker.js’);

worker.onmessage = (event) => { 

  console. log (‘Data from worker:’ , event.data ); 

};

worker. postMessage (‘start heavy computation’); 
Enter fullscreen mode Exit fullscreen mode

7. Optimizing Images and Assests

For Angular performance optimization it is essential to optimize your app assets like images. Angular offers CLI to minimize the size of static files and compress assets. Although Angular vs AngularJS might sound different but it's crucial to optimize images in both cases.

8. Network Requests Optimization

Network requests can be efficiently managed by HTTP interceptors with the help of the following command ensuring enhanced performance:

@Injectable () 

export class CacheInterceptor implements HttpInterceptor { 

  Intercept (req: HttpRequest <any>, next: HttpHandler ): Observable <HttpEvent <any>> { 

    if ( this.  isCached (req)) { 

      return of (this. getCachedData (req)); 

    }

    return next. Handle (req); 

  }

}
Enter fullscreen mode Exit fullscreen mode

Wrapping Up

A sound knowledge and experience of Angular framework is required for Angular performance optimization. I have explained all tried and tested techniques for performance optimization from lazy loading, change detection optimization, to assets and network requests optimization. So that, you can also leverage these strategies to run your Angular applications faster.

Top comments (0)