FormBuilder

Stable Class

What it does

Creates an AbstractControl from a user-specified configuration.

It is essentially syntactic sugar that shortens the new FormGroup(), new FormControl(), and new FormArray() boilerplate that can build up in larger forms.

How to use

To use, inject FormBuilder into your component class. You can then call its methods directly.

import {Component, Inject} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

@Component({
  selector: 'example-app',
  template: `
    <form [formGroup]="form">
      <div formGroupName="name">
        <input formControlName="first" placeholder="First">
        <input formControlName="last" placeholder="Last">
      </div>
      <input formControlName="email" placeholder="Email">
      <button>Submit</button>
    </form>

    <p>Value: {{ form.value | json }}</p>
    <p>Validation status: {{ form.status }}</p>
  `
})
export class FormBuilderComp {
  form: FormGroup;

  constructor(@Inject(FormBuilder) fb: FormBuilder) {
    this.form = fb.group({
      name: fb.group({
        first: ['Nancy', Validators.minLength(2)],
        last: 'Drew',
      }),
      email: '',
    });
  }
}

Class Overview

class FormBuilder {
  group(controlsConfig: {[key: string]: any}, extra?: {[key: string]: any}) : FormGroup
  control(formState: Object, validator?: ValidatorFn|ValidatorFn[], asyncValidator?: AsyncValidatorFn|AsyncValidatorFn[]) : FormControl
  array(controlsConfig: any[], validator?: ValidatorFn, asyncValidator?: AsyncValidatorFn) : FormArray
}

Class Description

Annotations

@Injectable()

Class Details

group(controlsConfig: {[key: string]: any}, extra?: {[key: string]: any}) : FormGroup

Construct a new FormGroup with the given map of configuration. Valid keys for the extra parameter map are validator and asyncValidator.

See the FormGroup constructor for more details.

control(formState: Object, validator?: ValidatorFn|ValidatorFn[], asyncValidator?: AsyncValidatorFn|AsyncValidatorFn[]) : FormControl

Construct a new 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.

array(controlsConfig: any[], validator?: ValidatorFn, asyncValidator?: AsyncValidatorFn) : FormArray

Construct a FormArray from the given controlsConfig array of configuration, with the given optional validator and asyncValidator.

exported from @angular/forms/index, defined in @angular/forms/src/form_builder.ts

doc_Angular
2016-10-06 09:46:30
Comments
Leave a Comment

Please login to continue.