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

Signals with Objects

Copy, then change.

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

A signal can hold a whole object, like a book with a title, a price, and a sale flag. The rule is the same as for arrays. Copy the object, then change the copy.

  • A whole object
  • Same rule as arrays
  • Copy, then change

Change or copy?

Changing a property of the object directly doesn't notify anyone. It's still the same object. Spread copies all the properties into a new object, and then we change the ones we want. The signal sees a new object, and notifies.

Don't

  • book().price = 5.99same objectnot notified

Do

  • update(b => ({ ...b, price: 5.99 }))a new objectnotified

A book on sale

Book is a signal holding a Book object. The template reads its properties, with book, brackets, dot title. Start sale makes a copy, with a new price, and the sale flag set. We click the button. Run it. The new price, and the sale label, appear.

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

interface Book { title: string; price: number; onSale: boolean }

@Component({
  selector: 'app-root',
  template: `
    <h2>{{ book().title }}</h2>
    <p>£{{ book().price }} {{ book().onSale ? '· On sale!' : '' }}</p>
    <button (click)="startSale()">Start the sale</button>
  `,
})
export class App {
  book = signal<Book>({ title: 'Persuasion', price: 7.49, onSale: false });

  startSale() {
    this.book.update(b => ({ ...b, price: 5.99, onSale: true }));
  }
}
Also uses actions.json
[{"click": "button"}]

Brackets inside update

Inside update, the arrow function returns an object. So we wrap the object in round brackets. Without them, TypeScript would think the curly braces start a function body. It's a small detail, that catches everyone once.

keyvalue
Returns an objectb => ({ ...b })
Round bracketsaround the object
Without them{ } is a function body
Spreadcopies every property

Summary

Signals can hold objects. Update them with a copy, using spread, and change only what's new. Next, linked signals.

Key takeaways
  • signal<Book>(...)
  • { ...b, price }
  • New object, notified
Next up: linkedSignal() — a value that resets