Angular4 Redux Forms

2017-12-17

Why Redux Forms?

  • Synchronized forms Using redux forms means your form will always be in sync with the redux store. Imagine a scenario where you accidentally close a modal form, you can re-open it and all your changes will still exist.
  • Angular support Is fully compatible with angular4 reactive and template forms, it just adds a thin layer that keeps your form in synch with the Redux store

Configuration

Run the command below to install the middle-ware

yarn add @angular-redux/form

Next open the app.module.ts file

import { NgModule } from '@angular/core';
import { NgReduxModule, NgRedux } from '@angular-redux/store';
mport { NgReduxFormModule } from '@angular-redux/form'; // <- Add this

@NgModule({
  imports: [
    NgReduxModule,
    NgReduxFormModule // <- Add this
  ],
  providers: [],
})
export class AppModule { }

Open your root-reducer.ts file and update to the following

import {togglesReducer as toggles} from './release-toggles/toggles.reducer';
import {combineReducers} from 'redux';
import {composeReducers, defaultFormReducer} from '@angular-redux/form'; // <- Add this

export const rootReducer = composeReducers(
  defaultFormReducer(),
  combineReducers({
    toggles
  })
);

Lets create a form

We are going to create a simple form with a select drop-down and an input field

<div>
    <form [connect]="['releaseToggles', 'editingToggle']">
        <section class="form-block">
            <div class="form-group">
                <label for="category">Category</label>
                <div class="select">
                    <select id="category"
                            name="category"
                            ngModel>
                        <option value="Unity">Unity</option>
                        <option value="Dashboard">Dashboard</option>
                        <option value="Titan">Titan</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label for="name">Name</label>
                <input id="name"
                        name="name"
                        type="text"
                        ngModel>
            </div>
        </section>
    </form>
</div>

Lets break this down. Lets look at this line first

<form [connect]="['releaseToggles', 'editingToggle']">

This line will automatically keep your form in synch with the Redux store. The array you pass it is a path to the place in store where you want to place your data.

<input id="name"
       name="name"
       type="text"
       ngModel>

The angular-redux/form plugin uses the name of the input to map to the redux store. So in this case if we start typing in this textfield we are also updating this path in memory

{
    releaseToggles: {
        editingToggle: {
            name: 'BlaBlaBla'
        }
    }
}

References

https://github.com/angular-redux/form

https://github.com/el-davo/angular-redux-saga