Easy Reactive Forms in Angular Using Formly

Formly has been a popular library for AngularJS to help with form creation and manipulation. Now, we can also enjoy Formly in Angular 2+ using @ngx-formly. It provides us with modules that make it easy to define almost any kind of reactive form using simple JSON objects.

If you're new to forms in Angular you may want to read here for our introduction to reactive forms.

Let’s briefly go over how to use Formly.

Setup

Formly can be used with Angular Material or Bootstrap, and here we’ll use it alongside Angular Material.

Let’s first install the necessary packages using npm or Yarn:

$ npm install @ngx-formly/core @ngx-formly/material

# or, using Yarn:
$ yarn add @ngx-formly/core @ngx-formly/material

Then we’ll setup a separate module for Material with the component modules we’ll need:

material.module.ts

import { NgModule } from '@angular/core';

import {
  MatButtonModule,
  MatInputModule,
  MatFormFieldModule,
  MatCheckboxModule,
  MatSelectModule
} from '@angular/material';

@NgModule({
  imports: [
    MatButtonModule,
    MatInputModule,
    MatFormFieldModule,
    MatCheckboxModule,
    MatSelectModule
  ],
  exports: [
    MatButtonModule,
    MatInputModule,
    MatFormFieldModule,
    MatCheckboxModule,
    MatSelectModule
  ]
})
export class MaterialModule {}

And then finally, in our app module let’s import our custom material module and the necessary modules for Formly:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { MaterialModule } from './material.module';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { ReactiveFormsModule } from '@angular/forms';
import { FormlyModule } from '@ngx-formly/core';
import { FormlyMaterialModule } from '@ngx-formly/material';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    ReactiveFormsModule,
    FormlyModule.forRoot(),
    FormlyMaterialModule,
    BrowserAnimationsModule,
    MaterialModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

Finally, unless you’re using a custom Material theme, make sure that you import one of the pre-built themes in your global styles file:

styles.css

@import '~https://fonts.googleapis.com/icon?family=Material+Icons';
@import '~@angular/material/prebuilt-themes/indigo-pink.css';

Usage

With all the properly modules imported in our app module, we’re ready to start using Formly and its formly-form component.

We can define a form in one of our components using two simple objects: a model with a key for each form field, and an object with an array of objects of type FormlyFieldConfig that contain configuration for each key in our model.

Let’s create a simple circus outfit order form to illustrate how to setup a form:

app.module.ts

import { Component } from '@angular/core';

import { FormGroup } from '@angular/forms';
import { FormlyFieldConfig } from '@ngx-formly/core';

@Component({ ... })
export class AppComponent {
  orderForm = new FormGroup({});

  // our model:
  order = {
    tagName: '',
    color: 'powder-blue', // will default to this value
    quantity: 1,
    size: 'M',
    terms: false
  };

  // our field configuration. Keys should match our model:
  orderFields: FormlyFieldConfig[] = [
    {
      key: 'tagName',
      type: 'input', // input type
      templateOptions: {
        type: 'text',
        label: 'Tag name for your outfit',
        placeholder: 'tag name'
      },
      validation: {
        messages: {
          maxLength: 'Tag name is too long'
        }
      },
      validators: {
        // limit to 25 characters
        maxLength: ({ value }) => {
          return value.length <= 25;
        }
      }
    },
    {
      key: 'color',
      type: 'select',
      templateOptions: {
        label: 'Outfit color',
        options: [
          { label: 'Powder blue', value: 'powder-blue' },
          { label: 'Orange crush', value: 'orange-crush' },
          { label: 'Purple haze', value: 'purple-haze' }
        ]
      }
    },
    {
      key: 'quantity',
      type: 'input',
      templateOptions: {
        type: 'number',
        label: 'How many outfits?',
        placeholder: 'quantity',
        required: true
      }
    },
    {
      key: 'size',
      type: 'select',
      defaultValue: 'M',
      templateOptions: {
        label: 'Size',
        options: [
          { label: 'Small', value: 'S' },
          { label: 'Medium', value: 'M' },
          { label: 'Large', value: 'L' }
        ]
      }
    },
    {
      key: 'terms',
      type: 'checkbox',
      templateOptions: {
        label: 'You accept our terms and conditions',
        required: true
      }
    }
  ];

  onSubmit(orderInfo) {
    console.log(orderInfo);
  }
}

The configuration can quickly get pretty long, but everything stays really simple and declarative. The above example demonstrates how to do a few very useful things:

  • Defining default values.
  • Easy custom validation and validation error massages.
  • Marking fields as required.
  • Specifying the field type and options in the case of select fields.

And then finally, the markup for the form in the component template couldn’t be simpler. We simply wrap our reactive form around a formly-form component to which we add inputs for our model and fields configuration objects:

app.component.html

<form [formGroup]="orderForm" (ngSubmit)="onSubmit(order)">
  <formly-form [model]="order" [fields]="orderFields">
    <button mat-raised-button color="primary" type="submit">
      Submit
    </button>
  </formly-form>
</form>

The formly-form component will dynamically create all of our configured form fields when the component initializes. Here’s what our example form looks like:

Our Formly form

🎪 That's it for our little intro! Have a look at the official website for more examples of what can be done using Formly.

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#