Lab 14: computed()
π Resourcesβ
π Starter Codeβ
step-14-album-wholesale-v21-post-signal-toSignal
In this lab, you'll create derived state using computed signals. You'll implement computed() to automatically calculate values like counts and totals from other signals, ensuring they update reactively when dependencies change.
π Instructionsβ
Step 1: Create Computed Signalβ
computed() derives a value from other signals:
import { signal, computed } from '@angular/core';
albums = signal<Album[]>([]);
albumCount = computed(() => this.albums().length);
Step 2: Use in Componentβ
Computed signals auto-update when dependencies change:
export class AlbumListComponent {
albums = toSignal(this.albumService.getAlbums(), { initialValue: [] });
albumCount = computed(() => this.albums().length);
totalPrice = computed(() =>
this.albums().reduce((sum, album) => sum + album.price, 0)
);
}
Step 3: Use in Templateβ
Call computed signals like regular signals:
<p>Total Albums: {{ albumCount() }}</p>
<p>Total Price: {{ totalPrice() | currency }}</p>