When an order's quantity goes from 1 to 2, how does Angular know which part of the page to change? The cart in the Services and DI lesson already used the answer, without saying much about it: signal.
A signal is a container for a value that announces when its value changes. From that announcement, Angular knows exactly which part of the page to update. Picture a small whiteboard on the cashier's desk at Jali's Pancake Stall, reading "Quantity: 1". As soon as the number is wiped and rewritten, everyone reading the board knows. The "Total" box on the receipt is calculated from the number on that board. A bell to the kitchen rings every time the number on the board changes. In Angular, the whiteboard is signal(), the Total box is computed(), and the bell is effect().
signal(): a container that announces changes
This component keeps the order's quantity in a signal:
import { Component, signal } from '@angular/core'
@Component({
selector: 'app-order',
standalone: true,
template: `
<p>Quantity: {{ quantity() }}</p>
<button (click)="increment()">+1</button>
<button (click)="reset()">Reset</button>
`,
})
export class Order {
quantity = signal(1)
increment() {
this.quantity.update((j) => j + 1)
}
reset() {
this.quantity.set(1)
}
}
| What happens | What runs | quantity() |
Shown |
|---|---|---|---|
| First shown | signal(1) |
1 | Quantity: 1 |
| Click +1 twice | update((j) => j + 1) |
3 | Quantity: 3 |
| Click Reset | set(1) |
1 | Quantity: 1 |
signal(1)creates a signal starting at 1, here namedquantity. You read a signal by calling it like a function:quantity(), in the class and in the template..set(value)replaces the value..update(fn)calculates the new value from the old one.- Angular records which template reads
quantity(). When that signal changes, Angular updates that template.set()with exactly the same value (for exampleset(1)when it's already 1) counts as no change.
computed(): a derived value that calculates itself
computed() creates a derived value: a value calculated from other signals. Here total comes from quantity and price:
price = 10
total = computed(() => this.quantity() * this.price)
quantity() |
total() |
|---|---|
| 1 | 10 |
| 3 | 30 |
computed()runs the function inside it, records which signals that function read (herequantity()), and keeps the result.- The result is reused until
quantitychanges. Even iftotal()is read twice in the template, the function still runs once. If another signal changes,totalisn't calculated again. - Only signals are recorded.
priceis a plain property here, so ifpriceis replaced,totalisn't calculated again. - A
computedis read-only. In an Angular CLI project, TypeScript refusesthis.total.set(0). In the exercise editor, it fails withTypeError: this.total.set is not a function.
effect(): running something when a signal changes
This effect() writes the latest quantity to the console:
constructor() {
effect(() => {
console.log('Quantity now:', this.quantity())
})
}
effect()runs once at the start, then every time a signal it read changes. In Angular 22 (the exercise editor), its first log line prints before its component's template is shown. In Angular 18, after.- If one click makes three changes (
set(2),set(3), thenupdate((j) => j + 1)),effect()runs only once, with the last value:Quantity now: 4. - Use
effect()for side effects (work outside the display), for example saving tolocalStorage(storage in the browser) or writing a log. To calculate a value, usecomputed. Angular 18 refuses a change to a signal inside aneffect:NG0600: Writing to signals is not allowed in a `computed` or an `effect` by default.Since Angular 19 it's allowed, in the exercise editor (Angular 22) too. But a derived value still reads more clearly as acomputed. - Like
inject()in the Services and DI lesson,effect()goes in theconstructoror on a class property.
An array inside a signal: replace it, don't change it
Say the cart is stored as cart = signal<number[]>([]): a signal holding an array of numbers, empty at the start. total = computed(...) adds up all the prices in it. The Order button runs this.cart().push(10). The template shows Items: {{ cart().length }} and Total: {{ total() }}.
push changes the array directly, without set() or update(), so the signal is never told. It announces nothing, and total keeps its old result.
| Click | Code | Items: |
Total: |
|---|---|---|---|
| 1 | this.cart().push(10) |
1 | 0 |
| 2 | this.cart().push(10) |
2 | 0 |
| 3 | this.cart.update((k) => [...k, 10]) |
3 | 30 |
So after two clicks the page shows Items: 2 and Total: 0. Items only goes up because Angular checks the template again after the click and reads the length of the same array. Always build a new array: update((k) => [...k, item]) or set([...this.cart(), item]). [...k, item] copies the contents of k into a new array, then adds item at the end. The form update((k) => { k.push(item); return k }) is just as wrong as push. A signal compares the old and new value with ===, and the returned array is still the same array, so it counts as no change.
Signals in a service: a shared cart
The cart from the Services and DI lesson already kept its contents in a signal. Now each item has a name and a price, and the total is calculated with computed:
import { Injectable, computed, signal } from '@angular/core'
export interface Item {
name: string
price: number
}
@Injectable({ providedIn: 'root' })
export class CartService {
items = signal<Item[]>([])
total = computed(() => this.items().reduce((t, item) => t + item.price, 0))
add(item: Item) {
this.items.update((items) => [...items, item])
}
}
interface Item describes the shape of each item: name is a string, price is a number. The menu card (MenuItem) calls add({ name: 'Special Egg Pancake', price: 10 }). The order summary (OrderSummary) writes {{ cart.items().length }} and {{ cart.total() }}. After Chocolate Cheese Pancake (8) and Special Egg Pancake are ordered, OrderSummary shows 2 items with a total of 18.
The exercises use the same shapes. The first exercise has count = signal(0), doubled = computed(() => this.count() * 2), and an increment() that runs this.count.update((c) => c + 1). So the first paragraph starts at Count: 0. The second exercise has name = signal('World') and greeting = computed(() => 'Hello, ' + this.name() + '!'), with <input [value]="name()" (input)="name.set(input.value)" #input />. So <h2> starts at Hello, World!.
Angular CLI projects also have signal forms of inputs and outputs: input(), output(), model(). The exercise editor and the Playground don't recognise them yet, so use @Input() and @Output() for now.
⚠️ Missing brackets and arrays that stay quiet
- Forgetting the parentheses. If the value is 2,
{{ quantity }}shows[Signal: 2], not 2. A signal is always read asquantity(). - An arrow function in the template. Since Angular 21.2, an arrow function in a template works, for example
(click)="quantity.update(j => j + 1)". It works in the exercise editor too (Angular 22). The arrow function's body must be one expression.j => { return j + 1 }, which uses curly braces, is refused withParser Error: Multi-line arrow functions are not supported. In Angular 21.1 and older, any arrow function makes the template fail to compile:Parser Error: Unexpected token > at column 20. If the logic takes more than one step, move it into a method, or write it without an arrow function:(click)="quantity.set(quantity() + 1)". - Changing an array's contents.
pushorspliceon an array inside a signal announces nothing, socomputedandeffectkeep using the old value. Build a new array. - Overwriting the signal.
this.quantity = 3replaces the signal with a plain number. A template callingquantity()fails withTypeError: ctx.quantity is not a function. Usethis.quantity.set(3). - Exercise detail. In the first exercise, the grader reads the first
<p>, soCount: ...must be the first paragraph, and there's only one button. In the second exercise, the grader typesSintainto the input box and waits for<h2>to readHello, Sinta!.
TL;DR: A signal is a container for a value that announces when its value changes. signal(1) creates a signal starting at 1. You read a signal named quantity by calling it, quantity(), and change it with .set() or .update(). Angular updates the parts of the template that read it. computed(() => ...) derives a value from other signals: it is calculated again only when those signals change, and it's read-only. effect() runs a side effect (work outside the display, such as writing a log) after a signal changes, once for several changes at a time. An array or object inside a signal must be replaced with a new one ([...k, item]: the old contents plus a new item). Changing the old array with push announces nothing, so a computed that adds it up keeps its old result. In a service, items = signal<Item[]>([]) (the list of ordered items) and total = computed(...) make a shared cart that's always in sync.
⚡ A signal is read by calling it
Write:
quantity = signal(1)
increment() {
this.quantity.update((j) => j + 1)
}
// template: <p>Quantity: {{ quantity() }}</p>
Guess first: after increment() runs once, quantity holds 2. If the template says {{ quantity }}, without brackets, what shows?
[Signal: 2], not 2. A signal is always read by calling it: quantity().
Meaning: A signal is a container for a value that announces when its value changes. signal(1) creates the signal quantity, starting at 1. .set() replaces the value, and .update() calculates the new value from the old one, here j + 1. Angular updates the parts of the template that read that signal.
In the first exercise, the paragraph showing Count: ... must be the first paragraph, and there's only one button.
⚡ computed() calculates itself
Write:
price = 10
total = computed(() => this.quantity() * this.price)
Meaning: computed() creates a value calculated from other signals. total holds quantity() times price, and it is calculated again only when quantity changes. total is read-only. A computed watches only signals, so if price (a plain property) is replaced, total isn't calculated again.
⚡ Arrays: replace, don't push
Write:
this.cart.update((k) => [...k, 10])
Guess first: cart is a signal holding an array of prices, empty at the start, and total is a computed that adds them up. If the Order button runs this.cart().push(10) twice, what number comes after Total: on the page?
Still 0. push changes the array directly, without set() or update(), so the signal is never told and announces nothing. total keeps its old result.
Meaning: In update(), a signal compares the old and new value with ===, and the same array counts as no change. So always build a new array: [...k, 10] copies the old contents of k into a new array, then adds 10.