Skip to content

Lab 13: computed()

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.

computed() derives a value from other signals:

import { signal, computed } from '@angular/core';
albums = signal<Album[]>([]);
albumCount = computed(() => this.albums().length);

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

Call computed signals like regular signals:

<p>Total Albums: {{ albumCount() }}</p>
<p>Total Price: {{ totalPrice() | currency }}</p>