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