Skip to main content

Lab 13: computed()

πŸ“– Resources​

πŸš€ Starter Code​

step-12-album-wholesale-v21-pre-control-flow

Continue from your Lab 13 result. If starting fresh, use step-12-album-wholesale-v21-pre-control-flow as your base and complete Labs 11–13 first.

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>