Giter VIP home page Giter VIP logo

ngrx-form's Introduction

ngrx-form npm version

Reactive Form bindings for NGRX.

See changelog for latest changes.

Whats this do?

Often when building Reactive Forms in Angular, you need to bind values from the store to form and vice versus. The values from the store are observable and the reactive form accepts raw objects, as a result we end up monkey patching this back and forth. For more info on this, checkout Reactive Forms with NGRX blog post.

Binding the values is not the only thing we commonly do, its not un-typical to translate form dirty status or form errors. Typical workflows might include reading the errors from the form to show in various decoupled components or for use in our effects or using the form dirty status to prevent users from leaving a page without saving but without binding a variable we have no way to reset the status of the form after a successful save from an effect.

In addition to these issues we encounter, there are workflows where you want to fill out a form and leave and then come back and resume your current status. This is an excellent use case for stores and we can conquer that case with this utility.

In a nutshell, this tool helps bridge the gaps between ngrx-store and reactive forms with a set of utilities and bindings to keep your forms and state in sync.

Usage

To get started, install the package:

npm i ngrx-form -s

Configuration

In the root module of your application, import NgrxFormModule and include it in the imports. Also in this file, lets import the form meta-reducer and bind it to our store.

import { form, NgrxFormModule } from 'ngrx-form';

@NgModule({
    StoreModule.forRoot(reducers, {
        metaReducers: [form]
    }),
    NgrxFormModule
})
export class AppModule {}

Reducer Setup

Define your state interface by extending the FormState interface:

import { FormState } from 'ngrx-form';

export interface PizzaForm extends FormState<Pizza> {}

the FormState interface is a interface you will map your form<=>model to. It looks like:

export interface FormState<T> {
  /**
   * The model to bind to the form
   */
  model: T;

  /**
   * Id of the model. Seperate because
   * this is typically not bound in
   * a form
   */
  modelId?: string;

  /**
   * Key value pair of errors
   */
  errors?: { [k: string]: string };

  /**
   * Whether the form is dirty or not.
   */
  dirty?: boolean;

  /**
   * The status of the form
   */
  status?: string;
}

then in the reducer populate the model object, this will vary based on your implementation but it should look something like this:

const pizzaDefaultState = { model: undefined };
export function pizzaReducer(state = pizzaDefaultState, action) {
    switch(action.type) {
        switch 'LOAD_PIZZA':
            return { ...state, model: action.payload };

        return state;
    }
}

Form Setup

In your component, you would implement the a reactive form and decorate the form with the ngrxForm directive with the path of your state object. We are passing the string path to ngrxForm. Our directive uses this path to connect itself to the store and setup bindings.

@Component({
    template: `
        <form [formGroup]="pizzaForm" novalidate (ngSubmit)="onSubmit()" ngrxForm="pizza">
            <input type="text" formControlName="toppings" />
            <button type="submit">Order</button>
        </form>
    `
})
export class PizzaComponent {
    pizzaForm = this.formBuilder.group({
        toppings: ['']
    });
}

Now anytime your form updates, your state will also reflect the new state.

The directive also has 2 inputs you can utilize as well:

  • ngrxFormDebounce: number - Debounce the value changes to the form. Default value: 100.
  • ngrxFormClearOnDestroy: boolean - Clear the state on destroy of the form.

Actions

In addition to it automatically keeping track of the form, you can also manually dispatch actions for things like resetting the form state. For example:

this.store.dispatch(
    new UpdateFormDirty({
        dirty: false, path: 'pizza'
    })
);

The actions that it comes with out of the box are:

  • UpdateFormStatus({ status, path }) - Update the form status
  • UpdateFormValue({ value, path }) - Update the form value
  • UpdateFormDirty({ dirty, path }) - Update the form dirty status
  • SetFormDisabled(path) - Set the form to disabled
  • SetFormEnabled(path) - Set the form to enabled
  • SetFormDirty(path) - Set the form to dirty (shortcut for UpdateFormDirty)
  • SetFormPristine(path) - Set the form to prestine (shortcut for UpdateFormDirty)

ngrx-form's People

Contributors

amcdnl avatar tpsb avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.