AI Hints
Home›Angular Tutorial›Signals with Objects, linkedSignal() and Practice: A Counter and a Basket
Angular · Lesson 36 of 120

Practice: A Counter and a Basket

Your turn.

⏱ 2 min read▶ Video at 43:49🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Let's practise signals. You'll build a small basket, with plus and minus buttons, and a total.

  • Plus and minus
  • A total
  • Your turn

A small basket

Your turn. Pause the video, and try this. Show a book, and a copies signal, starting at zero. Plus adds one, and minus takes one away, but never below zero. Show a computed total, and a message, when the basket is empty. Here is one solution. Copies is a signal, and update changes it. Math dot max keeps it from going below zero. Total is computed from the copies. After three clicks on plus, three copies cost twenty pounds ninety seven.

✍️ Exercise: A small basket

Signal copies = 0. + and − buttons (never below 0). computed total = copies × 6.99. Show "Your basket is empty" when copies is 0.

Show hint

copies.update(c => Math.max(0, c - 1)) and computed(() => this.copies() * this.price)

Show solution
app.tstypescript
import { Component, signal, computed } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <h2>Emma · £{{ price }}</h2>
    <button id="minus" (click)="copies.update(c => Math.max(0, c - 1))">−</button>
    <button id="plus" (click)="copies.update(c => c + 1)">+</button>
    <p>Copies: {{ copies() }}</p>
    <p>Total: £{{ total().toFixed(2) }}</p>
    <p>{{ copies() === 0 ? 'Your basket is empty' : 'Ready to check out' }}</p>
  `,
})
export class App {
  protected Math = Math;
  price = 6.99;
  copies = signal(0);
  total = computed(() => this.copies() * this.price);
}

What module four taught

Signals hold values, and notify when they change. Set, and update, change them. Computed works out values from other signals. Effects run code on changes. And arrays, and objects, are replaced with copies.

keyvalue
signal()a value that notifies
set / updatechange it
computed / linkedSignalderived values
Arrays, objectscopy, don't change

Summary

You can now keep data, and the page, in sync with signals. That's the end of module four. Next, control flow, at if, and at for.

Key takeaways
  • Signals
  • computed
  • Copies, not changes
Next up: @if — show or hide