Skip to main content

Lab 06: OnPush Change Detection

πŸ“– Resources​

πŸš€ Starter Code​

step-6-album-wholesale-v16-post-add-custom-component

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​

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​

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​

Always create new objects/arrays:

// βœ… Good: Create new array
this.albums.next([...currentAlbums, newAlbum]);

// ❌ Bad: Mutate existing array
currentAlbums.push(newAlbum);
this.albums.next(currentAlbums);