Sub topic 10
linkedSignal for state that resets
This chapter assumes you know signal(), computed() and effect() from the earlier chapters, and basic Angular components and templates.
The problem: derived state you also want to edit
A computed() signal is read-only. Sometimes you need a value that follows other signals but that the user can also overwrite. A typical case is a selected option in a list. When the list changes, the selection should reset. Between changes, the user should be able to pick something else.
Without linkedSignal(), you would write an effect() that calls set() on a writable signal whenever the source changes. That works, but it makes state flow through a side effect, which the earlier chapter on choosing between computed, effect and event handlers advises against.
What linkedSignal is
linkedSignal() creates a writable signal whose value is computed from other signals. It has two parts:
- A computation that produces the value from its source signals. This is what
computed()does. - The
set()andupdate()methods of a writable signal, so you can override the value.
Whenever a signal read by the computation changes, the computation runs again and replaces any value you set by hand.
import { signal, linkedSignal } from '@angular/core';
const options = signal(['Standard', 'Express', 'Pickup']);
const selected = linkedSignal(() => options()[0]);
console.log(selected()); // 'Standard'
selected.set('Express');
console.log(selected()); // 'Express'
options.set(['Courier', 'Locker']);
console.log(selected()); // 'Courier' (the manual choice was discarded)Like computed(), a linked signal is lazy and memoized. It recalculates only when it is read after a source has changed.
Keeping the previous value
The short form always resets. The object form lets you decide, because the computation receives the previous state. It has a source signal, or function, and a computation function. The computation gets the new source value and an optional previous object. previous is undefined on the first run. After that it holds the old source and the old value.
This example keeps the user's choice if it still exists in the new list:
import { signal, linkedSignal } from '@angular/core';
const options = signal(['Standard', 'Express', 'Pickup']);
const selected = linkedSignal({
source: options,
computation: (newOptions, previous) => {
if (previous && newOptions.includes(previous.value)) {
return previous.value;
}
return newOptions[0];
},
});
selected.set('Pickup');
options.set(['Pickup', 'Courier']);
console.log(selected()); // 'Pickup' (still available, so it is kept)
options.set(['Courier', 'Locker']);
console.log(selected()); // 'Courier' (no longer available, so it resets)Only the signals read in source trigger the computation. This keeps the dependencies explicit.
In a component
A linked signal works well when an input drives local state. Here the quantity starts from an input and resets when the input changes, but the user can still adjust it.
import { Component, input, linkedSignal } from '@angular/core';
@Component({
selector: 'app-quantity-picker',
template: `
<button (click)="decrement()">-</button>
<span>{{ quantity() }}</span>
<button (click)="increment()">+</button>
`,
})
export class QuantityPickerComponent {
defaultQuantity = input(1);
quantity = linkedSignal(() => this.defaultQuantity());
increment() {
this.quantity.update((q) => q + 1);
}
decrement() {
this.quantity.update((q) => Math.max(0, q - 1));
}
}computed or linkedSignal?
| Question | Use |
|---|---|
| Is the value always a pure function of other signals? | `computed()` |
| Must the user or code be able to overwrite it? | `linkedSignal()` |
| Should an overwrite survive a source change? | `linkedSignal()` with `source` and `computation` |
| Do you only need to run a side effect? | `effect()` |
Common errors
- Expecting
set()to last forever. Any change to a source signal discards the manual value, even when the new source value looks similar to the old one. - Reading extra signals in the short form. In
linkedSignal(() => ...), every signal read inside is a dependency. Use thesourceform when you want to control exactly which signal triggers a reset. - Using
previouson the first run.previousisundefinedthe first time, so check it before readingprevious.value. - Reaching for
effect()plusset(). If the only purpose of the effect is to write another signal, a linked signal is usually the better fit.
Exercise
A product page has a sizes = signal(['S', 'M', 'L']) signal. You want chosenSize to default to the first size, let the user pick another with set(), and keep the user's pick when sizes changes, as long as that size is still in the list. Which API do you use, and what does the computation do?
Show answer
Use linkedSignal({ source: sizes, computation: (newSizes, previous) => ... }). In the computation, return previous.value when previous exists and newSizes.includes(previous.value). Otherwise return newSizes[0]. A plain computed() cannot be set by the user. The short form linkedSignal(() => sizes()[0]) would reset the pick on every change to sizes.