Angular Performance Optimization: Best Practices for 2024
Angular Performance Optimization: Best Practices for 2024
Angular applications can achieve exceptional performance when optimized correctly. In this comprehensive guide, I'll share the most effective strategies I've implemented across numerous enterprise projects over my 20+ years of development experience.
OnPush Change Detection Strategy
One of the most impactful optimizations you can implement is the OnPush change detection strategy:
@Component({
selector: 'app-user-card',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="user-card">
<h3>{{ user.name }}</h3>
<p>{{ user.email }}</p>
</div>
`
})
export class UserCardComponent {
@Input() user!: User;
}
This strategy ensures Angular only checks the component when:
- Input properties change
- Events are triggered
- Observables emit new values
Lazy Loading and Code Splitting
Implement lazy loading for feature modules to reduce initial bundle size:
const routes: Routes = [
{
path: 'users',
loadChildren: () => import('./users/users.module').then(m => m.UsersModule)
},
{
path: 'products',
loadComponent: () => import('./products/products.component').then(c => c.ProductsComponent)
}
];
Virtual Scrolling for Large Lists
When dealing with large datasets, virtual scrolling is essential:
<cdk-virtual-scroll-viewport itemSize="50" class="viewport">
<div *cdkVirtualFor="let item of items">{{ item.name }}</div>
</cdk-virtual-scroll-viewport>
TrackBy Functions
Always use trackBy functions in *ngFor loops to help Angular identify which items have changed:
@Component({
template: `
<div *ngFor="let user of users; trackBy: trackByUserId">
{{ user.name }}
</div>
`
})
export class UserListComponent {
trackByUserId(index: number, user: User): number {
return user.id;
}
}
Bundle Analysis and Tree Shaking
Regularly analyze your bundles using the Angular CLI:
ng build --configuration production --source-map
npx webpack-bundle-analyzer dist/your-app/stats.json
Preloading Strategies
Implement smart preloading for better user experience:
RouterModule.forRoot(routes, {
preloadingStrategy: PreloadAllModules
})
Key Takeaways
- Use OnPush change detection for components that don't need frequent updates
- Implement lazy loading for feature modules
- Use virtual scrolling for large lists
- Always use trackBy functions in ngFor loops
- Analyze and optimize your bundles regularly
- Implement preloading strategies based on user behavior
These optimizations have helped me achieve Lighthouse scores above 90 on multiple enterprise applications. The key is to measure first, optimize second, and always validate your improvements with real metrics.
Have you implemented any of these techniques in your Angular projects? I'd love to hear about your experiences in the comments below!
Compartir este post