0 day streak
javascript / expert
Snippet

Synchronizing State with Linked Signals for Controlled Mutability

A linkedSignal is a writable signal that automatically resets or recalculates its value whenever a source signal changes. Unlike computed signals, which are read-only, linkedSignals allow for manual updates while maintaining a declarative dependency for their 'default' state.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { signal, linkedSignal } from '@angular/core';
export class ProductManager {
categories = signal(['Electronics', 'Books']);
selectedCategory = signal('Electronics');
// Resets sub-selection whenever the parent category changes
selectedProduct = linkedSignal({
source: this.selectedCategory,
computation: (cat) => `First ${cat} Item`
});
manualOverride(name: string) {
// Unlike computed(), linkedSignal is writable
this.selectedProduct.set(name);
}
}
angular
Breakdown
1
source: this.selectedCategory
The signal that triggers a reset of the linkedSignal when its value changes.
2
computation: (cat) => ...
A function that determines the new value of the signal based on the source change.
3
this.selectedProduct.set(name);
Demonstrates that linkedSignal is writable, allowing UI state to diverge from the default computation.