Skip to main content

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>