In our dynamic forms lessons we obviously didn’t account for all the various edge cases you might come across. Therefore if you need a more complex setup you might want to take a look at ngx-formly. Formly has been a very popular library even in AngularJS 1.x for rendering dynamic forms.

Ngx-formly is the Angular (2+) counterpart for doing this job. In this lesson we’ll quickly give it a look at how to transform our custom dynamic form rendering to use ngx-formly. For more use cases definitely check out the official ngx-formly repository on GitHub.

 

Add module to the root:

import {NgModule} from '@angular/core';
import {ReactiveFormsModule} from '@angular/forms';
import {FormlyModule} from '@ngx-formly/core';
import {FormlyBootstrapModule} from '@ngx-formly/bootstrap';

// for material2 import `FormlyMaterialModule`:
// import {FormlyMaterialModule} from '@ngx-formly/material';

@NgModule({
  imports: [
    ...,
    ReactiveFormsModule,
    FormlyModule.forRoot(),
    FormlyBootstrapModule,

    // for material2 use:
    // FormlyMaterialModule
  ],
})
export class AppModule {}

 

One difference from angular-formly with ngx-formly is the validation:

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

@Component({
  selector: 'app-root',
  template: `
    <h1>Dynamic reactive forms in Angular</h1>
    <app-dynamic-form [data]="person" [formDataObj]="personFields"></app-dynamic-form>
  `
})
export class AppComponent {
  person = {
    firstname: 'Juri',
    age: 32,
    gender: 'M'
  };

  personFields = <FormlyFieldConfig>[
    {
      key: 'firstname',
      type: 'input',
      templateOptions: {
        label: 'Firstname'
      },
      validators: {
        validation: Validators.required
      },
      validation: {
        messages: {
          required: 'You need to provide a value'
        }
      }
    },
    {
      key: 'age',
      type: 'input',
      templateOptions: {
        label: 'Age',
        type: 'number'
      },
      validators: {
        validation: Validators.min(18)
      },
      validation: {
        messages: {
          min: 'You need to specify a value greater or equal to 18'
        }
      }
    },
    {
      key: 'gender',
      type: 'radio',
      templateOptions: {
        label: 'Gender',
        options: [{ value: 'Male', key: 'M' }, { value: 'Female', key: 'F' }]
      }
    }
  ];
}

More infromation to check out.