Skip to content

Lab 06: OnPush Change Detection

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.

Add ChangeDetectionStrategy.OnPush to component:

import { ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'app-album-card',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AlbumCardComponent {
@Input() album!: Album;
}

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>

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);