From 27a678a09324ddb38b875217fbfebd91da21cfd7 Mon Sep 17 00:00:00 2001 From: Dany Marques Date: Fri, 29 Nov 2024 09:08:37 +0100 Subject: [PATCH] docs(core): improve computation example (#58965) PR Close #58965 --- .../content/guide/signals/linked-signal.md | 35 ++++++++++++++++--- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/adev/src/content/guide/signals/linked-signal.md b/adev/src/content/guide/signals/linked-signal.md index 8a3c00e83ce..3769caf3f49 100644 --- a/adev/src/content/guide/signals/linked-signal.md +++ b/adev/src/content/guide/signals/linked-signal.md @@ -59,9 +59,24 @@ In some cases, the computation for a `linkedSignal` needs to account for the pre 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_: ```typescript +interface ShippingMethod { + id: number; + name: string; +} + @Component({/* ... */}) export class ShippingMethodPicker { - shippingOptions: Signal = getShippingOptions(); + constructor() { + this.changeShipping(2); + this.changeShippingOptions(); + console.log(this.selectedOption()); // {"id":2,"name":"Postal Service"} + } + + shippingOptions: WritableSignal = signal([ + { id: 0, name: 'Ground' }, + { id: 1, name: 'Air' }, + { id: 2, name: 'Sea' }, + ]); selectedOption = linkedSignal({ // `selectedOption` is set to the `computation` result whenever this `source` changes. @@ -69,12 +84,22 @@ export class ShippingMethodPicker { computation: (newOptions, previous) => { // If the newOptions contain the previously selected option, preserve that selection. // Otherwise, default to the first option. - return newOptions.find(opt => opt.id === previous?.value?.id) ?? newOptions[0]; - } + return ( + newOptions.find((opt) => opt.id === previous?.value.id) ?? newOptions[0] + ); + }, }); - changeShipping(newOptionIndex: number) { - this.selectedOption.set(this.shippingOptions()[newOptionIndex]); + changeShipping(index: number) { + this.selectedOption.set(this.shippingOptions()[index]); + } + + changeShippingOptions() { + this.shippingOptions.set([ + { id: 0, name: 'Email' }, + { id: 1, name: 'Sea' }, + { id: 2, name: 'Postal Service' }, + ]); } } ```