#InputSignal default value from an observable

12 messages · Page 1 of 1 (latest)

boreal bay
#

input signals are new and since there aren't a lot of examples for specific cases, i was wondering if this is acceptable or are there some hidden stuff in the api that can make it better,

basically i have an input signal called show but i want to give it a default value, that default value is the && of two boolean observables

show: InputSignal<boolean> = input(
    toSignal(this.someObservableThatReturnsABoolean)()
    &&
    toSignal(this.anotherObservableThatReturnsABoolean)()
);

i know about computed but idk if it's of any use here
i guess i can use rxjs to get a single observable but i was wondering if it can be simpler
and just the fact that i'm get turning an observable to a signal and getting the value of that signal and then passing it to input which is a signal is kinda weird and doesn't feel right

lofty sail
#

Initializing the input from an Observable doesn't feel right in general. input() should represent the value coming from the external developer. If you want to mix in other sources to determine what the component should do, using a computed would be ideal.

boreal bay
#

the idea behind this is these two observables are used a lot and are the basically default so i don't want to use them everywhere and wanted to put it in this component

lofty sail
#

Yeah, that part seems reasonable. Don't be afraid to split your state though into inputs + derived state from inputs and other sources.

boreal bay
#

i ended up with this, idk if it needs more improvement, seems readable at least

  private hasSomething: Signal<boolean> = toSignal(
    this.store.pipe(select(selectSomething))
  );
  private hasSomethingElse: Signal<boolean> = toSignal(
    this.store.pipe(select(selectSomethingElse))
  );
  show: InputSignal<boolean> = input(
    this.hasSomething() && this.hasSomethingElse()
  );
lofty sail
#

Do you have strict null checks disabled in your codebase?

private hasSomething: Signal<boolean> = toSignal(
  this.store.pipe(select(selectSomething))
);

Should not compile. TypeScript should complain that toSignal(...)'s return type there is Signal<boolean | undefined> which is not assignable to the type you've given for hasSomething.

boreal bay
#

yeah, i just noticed it

#

it's not a personal project, but someone at work made it that way

lofty sail
#

In any case, I would still prefer a computed:

show = input<boolean>();
showWithDefault = computed(() => this.show() ?? (this.hasSomething() || this.hasSomethingElse()) ?? false);
#

That way, if hasSomething or hasSomethingElse changes at all, the default value gets properly updated.

boreal bay
#

ooh that's niiice, computed makes the most sense here