Tutorial

Reactive Forms in Angular Using Formly

Published on December 20, 2017
Default avatar

By Alligator.io

Reactive Forms in Angular Using Formly

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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';

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';

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
      }
    }
  ];

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.
  • 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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Alligator.io

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel