Lab 06: OnPush Change Detection
📖 Resources
Section titled “📖 Resources”🚀 Starter Code
Section titled “🚀 Starter Code”step-5-album-wholesale-v16-post-add-custom-async-validator
Continue from your Lab 05 result. If you need a fresh copy, use step-5-album-wholesale-v16-post-add-custom-async-validator as your starting point and complete Lab 05 first.
In this lab, you’ll optimize component performance by implementing OnPush change detection strategy. You’ll configure components to use OnPush, work with observables and the async pipe, and ensure state updates follow immutability patterns.
📝 Instructions
Section titled “📝 Instructions”Step 1: Enable OnPush
Section titled “Step 1: Enable OnPush”Add ChangeDetectionStrategy.OnPush to component:
import { ChangeDetectionStrategy } from '@angular/core';
@Component({ selector: 'app-album-card', changeDetection: ChangeDetectionStrategy.OnPush})export class AlbumCardComponent { @Input() album!: Album;}Step 2: Use Observables with Async Pipe
Section titled “Step 2: Use Observables with Async Pipe”OnPush works best with Observables and async pipe:
albums$ = this.albumService.getAlbums();<app-album-card *ngFor="let album of albums$ | async" [album]="album"></app-album-card>Step 3: Update State Immutably
Section titled “Step 3: Update State Immutably”Always create new objects/arrays:
// ✅ Good: Create new arraythis.albums.next([...currentAlbums, newAlbum]);
// ❌ Bad: Mutate existing arraycurrentAlbums.push(newAlbum);this.albums.next(currentAlbums);
