Skip to content

Commit 27a678a

Browse files
danymarquesthePunderWoman
authored andcommitted
docs(core): improve computation example (angular#58965)
PR Close angular#58965
1 parent f90dc69 commit 27a678a

File tree

1 file changed

+30
-5
lines changed

1 file changed

+30
-5
lines changed

adev/src/content/guide/signals/linked-signal.md

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -59,22 +59,47 @@ In some cases, the computation for a `linkedSignal` needs to account for the pre
5959
In the example above, `selectedOption` always updates back to the first option when `shippingOptions` changes. You may, however, want to preserve the user's selection if their selected option is still somewhere in the list. To accomplish this, you can create a `linkedSignal` with a separate _source_ and _computation_:
6060

6161
```typescript
62+
interface ShippingMethod {
63+
id: number;
64+
name: string;
65+
}
66+
6267
@Component({/* ... */})
6368
export class ShippingMethodPicker {
64-
shippingOptions: Signal<ShippingMethod[]> = getShippingOptions();
69+
constructor() {
70+
this.changeShipping(2);
71+
this.changeShippingOptions();
72+
console.log(this.selectedOption()); // {"id":2,"name":"Postal Service"}
73+
}
74+
75+
shippingOptions: WritableSignal<ShippingMethod[]> = signal([
76+
{ id: 0, name: 'Ground' },
77+
{ id: 1, name: 'Air' },
78+
{ id: 2, name: 'Sea' },
79+
]);
6580

6681
selectedOption = linkedSignal<ShippingMethod[], ShippingMethod>({
6782
// `selectedOption` is set to the `computation` result whenever this `source` changes.
6883
source: this.shippingOptions,
6984
computation: (newOptions, previous) => {
7085
// If the newOptions contain the previously selected option, preserve that selection.
7186
// Otherwise, default to the first option.
72-
return newOptions.find(opt => opt.id === previous?.value?.id) ?? newOptions[0];
73-
}
87+
return (
88+
newOptions.find((opt) => opt.id === previous?.value.id) ?? newOptions[0]
89+
);
90+
},
7491
});
7592

76-
changeShipping(newOptionIndex: number) {
77-
this.selectedOption.set(this.shippingOptions()[newOptionIndex]);
93+
changeShipping(index: number) {
94+
this.selectedOption.set(this.shippingOptions()[index]);
95+
}
96+
97+
changeShippingOptions() {
98+
this.shippingOptions.set([
99+
{ id: 0, name: 'Email' },
100+
{ id: 1, name: 'Sea' },
101+
{ id: 2, name: 'Postal Service' },
102+
]);
78103
}
79104
}
80105
```

0 commit comments

Comments
 (0)