Skip to content

RFC: withForms #4919

@gjanvier

Description

@gjanvier

Which @ngrx/* package(s) are relevant/related to the feature request?

signals

Information

Hello there,

I find signalStore great and use it on my professional projets. One of my very common use-case is to handle a list of items in my store, and handle a SearchComponent that simply filter what is displayed in my MainComponent.

My favorite pattern regarding such form is:

  • The use of Reactive Forms
  • That form should belong to the Store
  • Any Search Component (or its sub-component) should inject that Store so that it can get access to its formControl
  • The current state of that form should easily be read / computed using Signals

For this purpose, I created a utility function withForms() that solves my concerns in a few lines.

const MyStore = signalStore(
  withState({ items: [] }),

  // Adds search, searchValue and searchChanges to our Store
  withForms(() => ({ search: makeMySearchForm() })),

  withComputed(({ items, searchValue }) => ({
    filteredItems: computed(() => {
      const text = searchValue();
      return items().filter((item) => item.includes(text));
    }),
  }))
);

Here is a demo: https://stackblitz.com/edit/stackblitz-starters-6gqjsgtc?file=src%2Fmain.ts

The code for withForms() is quite simple but very convenient. Yet I don't know if it is worth being part of ngrx/signals? ;-)

Features:

  • adds 1 or many Form (FormControl, FormGroup) to the Store props
  • adds 1 or many Signals (pattern is: ${nameOfTheForm}Value, with the appropriate type hints
  • adds 1 or many Observable for form changes (pattern is: ${nameOfTheForm}Changes) with type hints
  • support debounceTime to avoid too many updates

Describe any alternatives/workarounds you're currently using

I used to keep the SearchComponent being responsible for instanciating such ReactiveForms and then updating my SignalStore with a "set" method, using an Observable, an Effect, etc.

Yet, bringing that Form into the SignalStore is so convenient, and so is a utility to transform that form into a Signal...

I would be willing to submit a PR to fix this issue

  • Yes
  • No

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions