AI Hints
Home›Angular Tutorial›What Signals Are, signal() and set() and update()
Angular · Lesson 30 of 120

set() and update()

Change a signal.

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

A signal is only useful if its value can change. There are two ways to change it, set, and update.

  • Values change
  • Two ways
  • set and update

Two ways to change

Set replaces the value with a new one. Update takes a function. The function gets the current value, and returns the new one. Use update when the new value depends on the old one.

keyvalue
set(1)replace the value
update(q => q + 1)new from old
Use setfor a fresh value
Use updatewhen it depends on the old

Plus, minus, and reset

Quantity starts at one. Minus, and plus, use update, to work from the current quantity. Reset uses set, because the new value doesn't depend on the old one. We click plus three times, and minus once. Run it. One, plus three, minus one, makes three.

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

@Component({
  selector: 'app-root',
  template: `
    <h2>Copies of Emma: {{ quantity() }}</h2>
    <button id="minus" (click)="quantity.update(q => q - 1)">−</button>
    <button id="plus" (click)="quantity.update(q => q + 1)">+</button>
    <button id="reset" (click)="quantity.set(1)">Reset</button>
  `,
})
export class App {
  quantity = signal(1);
}
Also uses actions.json
[{"click": "#plus", "times": 3}, {"click": "#minus"}]

Signal rules

Change signals only with set, or update. Never try to assign to a signal. Keep each signal small, and focused. And name it after what it holds, like quantity, or stock.

keyvalue
Change withset() or update()
Neverquantity = 3
Keepsmall and focused
Namewhat it holds

Summary

Set replaces a signal's value, and update works out the new value from the old one. Next, computed signals.

Key takeaways
  • set(1)
  • update(q => q + 1)
  • Page updates
Next up: computed() — values from values