angularngrxangular-signals

Reuse a computed signal in NGRX signal store


In NGRX signal store, I want to reuse the computed value in another computed value that is in withComputed.

For example:

export const ExampleStore = signalStore(
  withState(initialState),
  withComputed(store => ({
    property1: computed(() => store.example()),
    property2: computed(() => store.property1()),
  }))
);

store.property1() is no callable in computed


Solution

  • There are 2 patterns I know of:

    Use a second withComputed

    export const ExampleStore = signalStore(
      withState(initialState),
      withComputed(store => ({
        property1: computed(() => store.example()),
      })),
      withComputed(store => ({
        property2: computed(() => store.property1()),
      }))
    );
    

    In the same withComputed

    export const ExampleStore = signalStore(
      withState(initialState),
      withComputed(store => {
        const property1 = computed(() => store.example());
        const property2 = computed(() => property1());
        
        return {property1, property2};
      })
    );