FormBuilder

Creates an AbstractControl from a user-specified configuration.

The FormBuilder provides syntactic sugar that shortens creating instances of a FormControl, FormGroup, or FormArray. It reduces the amount of boilerplate needed to build complex forms.

Links & Tutorials

Generating form controls

The FormBuilder service has three methods: control(), group(), and array(). These are factory methods for generating instances in your component classes including form controls, form groups, and form arrays.

import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { ValidationService } from 'app/validation.service';

@Component({
  selector: 'demo-app',
  templateUrl: 'app/app.component.html'
})
export class AppComponent {
  userForm: any;

  constructor(private formBuilder: FormBuilder) {
    this.userForm = this.formBuilder.group({
      name: ['', Validators.required],
      email: ['', [Validators.required, ValidationService.emailValidator]],
      profile: ['', [Validators.required, Validators.minLength(10)]]
    });
  }

  saveUser() {
    if (this.userForm.dirty && this.userForm.valid) {
      alert(
        `Name: ${this.userForm.value.name} Email: ${this.userForm.value.email}`
      );
    }
  }
}

Interface

group#

group(controlsConfig: {[key: string]: any}, options: AbstractControlOptions|{[key: string]: any}|null = null): FormGroup

Construct a new FormGroup instance.

control#

control(formState: any, validatorOrOpts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions|null, asyncValidator?: AsyncValidatorFn|AsyncValidatorFn[]|null): FormControl

Construct a new FormControl with the given state, validators and options.

Initialize a control as disabled

The following example returns a control with an initial value in a disabled state.

import {Component, Inject} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
/* . . . */
@Component({
  selector: 'app-disabled-form-control',
  template: `
    <input [formControl]="control" placeholder="First">
  `
})
export class DisabledFormControlComponent {
  control: FormControl;

  constructor(private fb: FormBuilder) {
    this.control = fb.control({value: 'my val', disabled: true});
  }
}

array#

array(controlsConfig: any[], validatorOrOpts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions|null, asyncValidator?: AsyncValidatorFn|AsyncValidatorFn[]|null): FormArray

Constructs a new FormArray from the given array of configurations, validators and options.