Performance Optimization
A fast application makes users happy. A slow one drives them away. Performance optimization is about making your Angular app load faster and run smoother.
1. Lazy Loading
We already covered this – load modules only when needed. This is the biggest performance win.
2. ChangeDetectionStrategy.OnPush
By default, Angular checks every component for changes on every event. With OnPush, Angular only checks when @Input() references change or events occur.
@Component({
changeDetection: ChangeDetectionStrategy.OnPush
})
3. trackBy with *ngFor
When lists change, *ngFor recreates all DOM elements by default. Use trackBy to tell Angular how to identify items uniquely.
<li *ngFor="let item of items; trackBy: trackById">{{ item.name }}</li>
trackById(index: number, item: any) {
return item.id;
}
4. Pure Pipes
Pipes are pure by default – they only run when input changes. Use pure pipes instead of methods in templates.
<!-- Bad - called on every change detection -->
<p>{{ getFormattedDate() }}</p>
<!-- Good - only runs when date changes -->
<p>{{ date | date:'fullDate' }}</p>
5. Unsubscribe from Observables
Memory leaks happen when you don't unsubscribe. Use async pipe or manage subscriptions.
// Using async pipe (automatic)
data$ = this.service.getData();
// Manual unsubscribe
private subscription: Subscription;
ngOnInit() {
this.subscription = this.service.getData().subscribe();
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
6. AOT Compilation
Ahead-of-Time compilation compiles during build, not in browser. It's enabled by default in production builds.
7. Bundle Size Optimization
- Remove unused dependencies.
- Use `ng build --prod --source-map=false` to disable source maps.
- Consider using `--build-optimizer`.
- Lazy load everything possible.
8. Image Optimization
- Use modern formats (WebP).
- Lazy load images below the fold.
- Set width and height to prevent layout shift.
9. Server-Side Rendering (Angular Universal)
For better initial load time and SEO, consider Angular Universal.
10. Web Workers
Move heavy computations off the main thread using web workers.
Two Minute Drill
- Lazy loading is #1 performance booster.
- Use OnPush change detection for components.
- Always use trackBy with *ngFor.
- Prefer pure pipes over methods in templates.
- Unsubscribe from observables or use async pipe.
- AOT compilation is essential for production.
- Optimize images and bundle size.
- Consider Angular Universal for SSR.
Need more clarification?
Drop us an email at career@quipoinfotech.com
