Connect Angular Forms to @ngrx/store
In this article, we will learn how to connect Angular forms to ngrx/store with ngrx/effects.
Our final result will be the following:
The Reducer
For the sake of simplicity we will use a single reducer to manage all the forms in our application.
The state will be composed of a simple object whose keys are the IDs, and the values are the forms data.
For example:
We will have one type of action — UPDATE_FORM
. The action payload will be an object with two keys, the path, and the value.
And the reducer will be responsible for updating the state.
ConnectForm Directive
Get The State
We want to update the form based on the state, so we need to take the path as Input
and query the right piece from the store.
We are grabbing the form directive instance via DI and updating the form value with the data from the store.
Update The State
We also need to update the form state when the form value changes. We can do this easily by subscribing to the valueChanges
observable and dispatch the UPDATE_FORM
action with the value.
That’s all we need for the form to be synchronized with the state.
Notifications and Reset
There are two things we want to achieve in this section:
- Display notification to the user based on the HTTP response — we are going to keep it local to the component and not store this information on the store, for two reasons:
- Usually, no other component is interested in this information.
- We don’t want to reset the state every time.
2. Reset the form when the submit succeed.
We will let Angular to do what it does best, handling the local validations and reset the form.
The Success Action
The success action takes the form path so we can know which form we need to reset and when to emit the success
event.
The Error Action
The error action takes the form path so we can know when to emit the error
event with the error.
We need to create the success
and error
outputs and listen to the FORM_SUBMIT_ERROR
and FORM_SUBMIT_SUCCESS
actions.
Because we are working with ngrx/effects, we can use the Actions
service for listening to actions.
And of course, we do not want to forget to clean up the subscriptions.
The final step is to invoke the form actions based on the response.
Now we can display the alerts in the component.
If you are not working with ngrx/effects, you can find a replacement solution in my previous article — Listening for Actions in @ngrx/store.
Follow me on Medium or Twitter to read more about Angular, Akita and JS!
🚀 Have You Tried Akita Yet?
One of the leading state management libraries, Akita has been used in countless production environments. It’s constantly developing and improving.
Whether it’s entities arriving from the server or UI state data, Akita has custom-built stores, powerful tools, and tailor-made plugins, which help you manage the data and negate the need for massive amounts of boilerplate code. We/I highly recommend you try it out.