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

linkedSignal()

A value that resets.

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

Imagine choosing a book, and then a quantity. When you choose a different book, the quantity should go back to one. Linked signal does exactly that.

  • Choose a book
  • Choose a quantity
  • Reset on a new book

linkedSignal

A linked signal can be set, and updated, like a normal signal. But it's linked to a source signal. Whenever the source changes, it's reset, using a computation. So it's writable, and it follows its source.

keyvalue
Writableset(), update()
sourcethe signal it follows
computationits value after a change
Use forchoices that depend on others

Quantity resets

Selected holds the chosen title. Quantity is linked to selected, and its computation returns one. We click one more twice, so Dune has three copies. Then we choose Emma. Run it. The start was Dune times one. And after choosing Emma, quantity went back to one, by itself.

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

@Component({
  selector: 'app-root',
  template: `
    <button (click)="selected.set('Dune')">Dune</button>
    <button id="emma" (click)="selected.set('Emma')">Emma</button>
    <h2>{{ selected() }} × {{ quantity() }}</h2>
    <button id="more" (click)="quantity.update(q => q + 1)">One more</button>
  `,
})
export class App {
  selected = signal('Dune');
  quantity = linkedSignal({ source: this.selected, computation: () => 1 });

  constructor() {
    console.log(`Start: ${this.selected()} × ${this.quantity()}`);
  }
}
Output
Start: Dune × 1
Also uses actions.json
[{"click": "#more", "times": 2}, {"click": "#emma"}]

Summary

Linked signals are writable, but reset whenever their source signal changes. Next, some practice.

Key takeaways
  • linkedSignal()
  • source
  • computation
Next up: Practice: A Counter and a Basket — your turn