Angular is a powerful framework for building complex applications, and performance is essential for a smooth user experience. Below are some advanced Angular performance optimization techniques, including trackBy for *ngFor, change detection strategies, lazy loading, and using pure pipes.
1. Using trackBy with *ngFor:
One of the most common operations in Angular applications is iterating over arrays using *ngFor. By default, *ngFor uses object references to track items within the array. When an item changes, Angular re-renders the entire list. This can lead to performance problems in large lists.
To tackle this issue, use the trackBy function with *ngFor. trackBy allows Angular to track the items in the list using a unique identifier, minimizing unnecessary DOM manipulations.
Here’s how to use trackBy:
<ng-container *ngFor="let item of items; trackBy: trackByFn">
<!-- item content -->
</ng-container>
And in your component:
trackByFn(index, item): number {
return item.id; // assuming 'id' is a unique identifier for each item
}
2. Change Detection Strategies:
Angular automatically runs change detection whenever an event is triggered, leading to potentially unnecessary checks. To optimize performance, change the change detection strategy from the default ‘ChangeDetectionStrategy.Default‘ to ‘ChangeDetectionStrategy.OnPush‘.
Use ‘OnPush‘ when a component’s data is immutable or its input bindings are updated less frequently. This helps limit the number of times Angular checks for changes.
import { Component, ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MyComponent {
// component logic
}
3. Lazy Loading:
Lazy loading helps you to split your application into smaller bundles, which will be loaded on-demand. This significantly reduces the initial loading time of your application. Angular provides a built-in solution for lazy loading using the Angular router.
In your AppRoutingModule, configure the loadChildren property:
const routes: Routes = [
{
path: 'lazy',
loadChildren: () =>
import('./lazy-module/lazy-module.module').then(
(m) => m.LazyModuleModule
),
},
];
4. Pure Pipes:
Pipes are a way to transform data in Angular templates. By default, pipes are pure, meaning they won’t be called again unless their input changes. Utilize pure pipes to reduce unnecessary calculations and improve performance.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'examplePipe'
})
export class ExamplePipe implements PipeTransform {
transform(value: any): any {
// transformation logic
}
}
And use it in the template:
<div>{{value | examplePipe}}</div>
5. AOT Compilation:
Angular provides an Ahead-of-Time (AOT) compiler to pre-compile your application’s components and templates into efficient JavaScript code during the build process. This decreases application load time by reducing the work required during runtime.
To use AOT compilation, add the ‘–aot‘ flag when building your application:
ng build --prod --aot
In conclusion, various optimization techniques like trackBy, change detection strategies, lazy loading, pure pipes, and AOT compilation can be used to improve the performance of Angular applications. Carefully consider which techniques to apply and how to combine them effectively for the best results in your specific application.