Welcome to our performance optimization deep dive! Let’s transform your Angular application from good to blazing fast with these professional-grade techniques.
1. Change Detection Strategies
OnPush Change Detection
typescript
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
changeDetection: ChangeDetectionStrategy.OnPush // ← Add this
})
What it does:
- Only checks component when:
- Input references change
- Events originate from the component
- Async pipes receive new values
- Change detection is triggered manually
Best for:
- Presentational components
- Components with immutable inputs
2. Lazy Loading Modules
typescript
// app-routing.module.ts
{
path: 'dashboard',
loadChildren: () => import('./dashboard/dashboard.module')
.then(m => m.DashboardModule)
}
Pro Tip: Add a preloading strategy:
typescript
RouterModule.forRoot(routes, {
preloadingStrategy: QuicklinkStrategy // or PreloadAllModules
})
3. Optimizing Template Binding
Avoid Function Calls in Templates
❌ Slow:
html
<div>{{ calculateTotal() }}</div>
✅ Better:
typescript
total$ = this.cartService.items$.pipe( map(items => this.calculateTotal(items)) );
html
<div>{{ total$ | async }}</div>
TrackBy in ngFor
html
<div *ngFor="let item of items; trackBy: trackById">
typescript
trackById(index: number, item: Item): number {
return item.id; // Unique identifier
}
4. Performance Budgets
Add to angular.json:
json
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
}
]
}
}
5. Bundle Analysis
bash
ng build --stats-json npx webpack-bundle-analyzer dist/stats.json
Key findings to look for:
- Large third-party libraries
- Duplicate dependencies
- Unused code
6. Optimizing Assets
Image Optimization
html
<img [src]="imageUrl" loading="lazy" width="800" height="600">
Tools:
- Squoosh (for manual optimization)
- ImageMin (for build process)
Font Loading
html
<link rel="preload" href="font.woff2" as="font" type="font/woff2" crossorigin>
7. Server-Side Rendering (SSR)
bash
ng add @nguniversal/express-engine
Benefits:
- Faster initial load
- Better SEO
- Social media previews
8. Web Workers for CPU-Intensive Tasks
typescript
// Create worker
const worker = new Worker('./app.worker', { type: 'module' });
// Communicate
worker.postMessage(data);
worker.onmessage = ({ data }) => {
console.log('Worker response:', data);
};
9. Advanced RxJS Optimization
typescript
data$ = this.route.params.pipe(
debounceTime(300), // Wait for pauses
distinctUntilChanged(), // Only if params change
switchMap(params => // Cancel previous requests
this.service.getData(params)
),
shareReplay(1) // Cache for subscribers
);
10. Production Build Optimizations
bash
ng build --prod
What it enables:
- Ahead-of-Time (AOT) compilation
- Tree-shaking
- Minification
- Dead code elimination
- Production mode (faster change detection)
Performance Audit Tools
- Lighthouse (Chrome DevTools)
- WebPageTest.org
- Angular DevTools (Change Detection Profiler)
- Source Map Explorer
Hands-On Optimization Challenge
Take an existing Angular app and:
- Identify 3 performance bottlenecks
- Implement OnPush change detection
- Add lazy loading for one feature module
- Optimize one slow template binding
- Analyze the bundle and remove one unused dependency
What’s Next?
In Part 14, we’ll explore Angular Testing Strategies – how to ensure your app works flawlessly!
