Can the following pattern be achieved in a simpler way?
Requirements:
- Writable signal input
- prioritize input values over the provided default signal
It feels weird calculating the first value since it should be the provided value when there is no input set. You kind of need to know if there was a input set.
const EXAMPLE_TOKEN = new InjectionToken<Signal<string>>('EXAMPLE_TOKEN');
@Component({
template: `{{ value() }}`,
})
class Example {
readonly providedValue = inject(EXAMPLE_TOKEN, {
optional: true,
});
readonly valueInput = input(
this.providedValue?.() ?? 'initial input value',
{
alias: 'value',
},
);
readonly value = linkedSignal({
source: this.valueInput,
computation: (higherPrioValue, previousValue) => {
if (!isSignal(this.providedValue)) {
return higherPrioValue;
}
const lowerPrioValue = this.providedValue();
/**
* The first value is always the higher priority value.
*
* If there is a new higher priority value, return it. If there is no
* new higher priority value, we know there is a new lower priority
* value.
*/
if (!previousValue || higherPrioValue !== previousValue.source) {
return higherPrioValue;
}
return lowerPrioValue;
},
});
}