FormGroup

Stable

Class

What it does

Tracks the value and validity state of a group of FormControl instances.

A FormGroup aggregates the values of each child FormControl into one object, with each control name as the key. It calculates its status by reducing the statuses of its children. For example, if one of the controls in a group is invalid, the entire group becomes invalid.

FormGroup is one of the three fundamental building blocks used to define forms in Angular, along with FormControl and FormArray.

How to use

When instantiating a FormGroup, pass in a collection of child controls as the first argument. The key for each child will be the name under which it is registered.

Example

const form = new FormGroup({ first: new FormControl('Nancy', Validators.minLength(2)), last: new FormControl('Drew'), }); console.log(form.value); // {first: 'Nancy', last; 'Drew'} console.log(form.status); // 'VALID'

You can also include group-level validators as the second arg, or group-level async validators as the third arg. These come in handy when you want to perform validation that considers the value of more than one child control.

Example

const form = new FormGroup({ password: new FormControl('', Validators.minLength(2)), passwordConfirm: new FormControl('', Validators.minLength(2)), }, passwordMatchValidator); function passwordMatchValidator(g: FormGroup) { return g.get('password').value === g.get('passwordConfirm').value ? null : {'mismatch': true}; }
  • npm package: @angular/forms

Class Overview

class FormGroup extends AbstractControl {
constructor(controls: {[key: string]: AbstractControl}, validator?: ValidatorFn, asyncValidator?: AsyncValidatorFn)

controls : {[key: string]: AbstractControl}
registerControl(name: string, control: AbstractControl) : AbstractControl
addControl(name: string, control: AbstractControl) : void
removeControl(name: string) : void
setControl(name: string, control: AbstractControl) : void
contains(controlName: string) : boolean
setValue(value: {[key: string]: any}, {onlySelf, emitEvent}?: {onlySelf?: boolean, emitEvent?: boolean}) : void
patchValue(value: {[key: string]: any}, {onlySelf, emitEvent}?: {onlySelf?: boolean, emitEvent?: boolean}) : void
reset(value?: any, {onlySelf, emitEvent}?: {onlySelf?: boolean, emitEvent?: boolean}) : void
getRawValue() : any

}

Class Description

Constructor

constructor(controls: {[key: string]: AbstractControl}, validator?: ValidatorFn, asyncValidator?: AsyncValidatorFn)

Class Details

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