Angular Forms - Form Builder

FormBuilder

By injecting FormBuilder in the constructor of our TS-file we can create our root/form FormGroup as easy as
constructor(fb: FormBuilder){
   this.form = fb.group([
      firstName: fb.control(),
      mobile: fb.control('079 123 45 67')
]);
}
instead of
constructor() {
   let controls = {};
   controls['firstName'] = new FormControl();
   controls['mobile'] = new FormControl('079 123 45 67');
   this.form = new FormGroup(controls);
}

FormBuilder - FormControl

/**
 * Construct a new {@link FormControl} with the given
 * `formState`,`validator`, and `asyncValidator`.
 *
 * `formState` can either be a standalone value for the
 * form control or an object that contains both
 * a value and a disabled status.
 */
 control(formState: any,
    validator?: ValidatorFn | ValidatorFn[] | null,
    asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]
       | null
 ): FormControl;

FormBuilder - FormGroup

/**
 * Construct a new {@link FormGroup} with the given map
 * of configuration.
 * Valid keys for the `extra` parameter map are
 * `validator` and `asyncValidator`.
 *
 * See the {@link FormGroup} constructor for more details.
 */
 group(controlsConfig: {
       [key: string]: any;
    }, extra?: {
       [key: string]: any;
    } | null
 ): FormGroup;

FormBuilder - FormArray

/**
 * Construct a {@link FormArray} from the given
 * `controlsConfig` array of configuration, with the
 * given optional `validator` and `asyncValidator`.
 */
 array(controlsConfig: any[],
    validator?: ValidatorFn | null,
    asyncValidator?: AsyncValidatorFn | null
 ): FormArray;

Example

constructor(fb: FormBuilder){
   this.form = fb.group([
      firstName: fb.control()
   ]);
}
<form [formGroup]="form" (ngSubmit)="onSubmit(form.value)">
      <label for="firstName">First name</label>
      <input id="firstName" formControlName="firstName">
</form>
  • form is the FormGroup we created using the FormBuilder in our TS-file
  • formControlName="firstName" represents the key of the FormControl firstName in our TS-file (form.firstName: FormControl)