Ayala
Ayala

Reputation: 141

Why use linkedSignal instead of computed in Angular Signals?

I am trying to understand the differences between linkedSignal and computed in Angular's Signals system, and why linkedSignal would be preferred in certain situations.

For example, if I want to manage a selectedOption that depends on shippingOptions, why not use computed like this:

const shippingOptions = signal(['Ground', 'Air', 'Sea']);
const selectedOption = computed(() => shippingOptions()[0]);

Why linkedSignal is a better choice in scenarios like this?

I haven't tried implementing this yet—I'm trying to understand the conceptual differences between linkedSignal and computed. Based on what I understand, computed should work fine for dependent state. I'm wondering what makes linkedSignal a better option in Angular's Signals system.

Upvotes: 13

Views: 1853

Answers (1)

Matthieu Riegler
Matthieu Riegler

Reputation: 55679

A linkedSignal is a writable signal that is already derived from another reactive expression.

Indeed :

const selectedOption = linkedSignal(() => shippingOptions()[0]);

is the same as

const selectedOption = computed(() => shippingOptions()[0]);

in terms of reading the signal and reacting to its changes.

But linked signal is also a WritableSignal, so you can write to it locally.

const selectedOption = linkedSignal(() => shippingOptions()[0]);
selectionOption('myNewValue'). 

Also the computation of the linkedSignal allows to access previous values :

const selectedOption = linkedSignal({
  source: shippingOptions(),
  computation: (newValue, previousValue) => { value[0] }
});

One of the usecases for linkedSignal is a local state in a component that depends on an input() but that also be written from inside the component itself, without exposing the inner state unlike what model would do.

Upvotes: 13

Related Questions