This is the archived documentation for Angular v6. Please visit angular.io to see documentation for the current version of Angular.

FormGroup

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

See more...

class FormGroup extends AbstractControl { constructor(controls: {...}, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null) controls: {...} 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: {...}, options: {...}): void patchValue(value: {...}, options: {...}): void reset(value: any = {}, options: {...}): void getRawValue(): any // inherited from forms/AbstractControl constructor(validator: ValidatorFn | null, asyncValidator: AsyncValidatorFn | null) value: any validator: ValidatorFn | null asyncValidator: AsyncValidatorFn | null parent: FormGroup | FormArray status: string valid: boolean invalid: boolean pending: boolean disabled: boolean enabled: boolean errors: ValidationErrors | null pristine: boolean dirty: boolean touched: boolean untouched: boolean valueChanges: Observable<any> statusChanges: Observable<any> updateOn: FormHooks root: AbstractControl setValidators(newValidator: ValidatorFn | ValidatorFn[] | null): void setAsyncValidators(newValidator: AsyncValidatorFn | AsyncValidatorFn[] | null): void clearValidators(): void clearAsyncValidators(): void markAsTouched(opts: {...}): void markAsUntouched(opts: {...}): void markAsDirty(opts: {...}): void markAsPristine(opts: {...}): void markAsPending(opts: {...}): void disable(opts: {...}): void enable(opts: {...}): void setParent(parent: FormGroup | FormArray): void abstract setValue(value: any, options?: Object): void abstract patchValue(value: any, options?: Object): void abstract reset(value?: any, options?: Object): void updateValueAndValidity(opts: {...}): void setErrors(errors: ValidationErrors | null, opts: {...}): void get(path: Array<string | number> | string): AbstractControl | null getError(errorCode: string, path?: string[]): any hasError(errorCode: string, path?: string[]): boolean }
      
      class FormGroup extends AbstractControl {
  constructor(controls: {...}, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null)
  controls: {...}
  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: {...}, options: {...}): void
  patchValue(value: {...}, options: {...}): void
  reset(value: any = {}, options: {...}): void
  getRawValue(): any

  // inherited from forms/AbstractControl
  constructor(validator: ValidatorFn | null, asyncValidator: AsyncValidatorFn | null)
  value: any
  validator: ValidatorFn | null
  asyncValidator: AsyncValidatorFn | null
  parent: FormGroup | FormArray
  status: string
  valid: boolean
  invalid: boolean
  pending: boolean
  disabled: boolean
  enabled: boolean
  errors: ValidationErrors | null
  pristine: boolean
  dirty: boolean
  touched: boolean
  untouched: boolean
  valueChanges: Observable<any>
  statusChanges: Observable<any>
  updateOn: FormHooks
  root: AbstractControl
  setValidators(newValidator: ValidatorFn | ValidatorFn[] | null): void
  setAsyncValidators(newValidator: AsyncValidatorFn | AsyncValidatorFn[] | null): void
  clearValidators(): void
  clearAsyncValidators(): void
  markAsTouched(opts: {...}): void
  markAsUntouched(opts: {...}): void
  markAsDirty(opts: {...}): void
  markAsPristine(opts: {...}): void
  markAsPending(opts: {...}): void
  disable(opts: {...}): void
  enable(opts: {...}): void
  setParent(parent: FormGroup | FormArray): void
  abstract setValue(value: any, options?: Object): void
  abstract patchValue(value: any, options?: Object): void
  abstract reset(value?: any, options?: Object): void
  updateValueAndValidity(opts: {...}): void
  setErrors(errors: ValidationErrors | null, opts: {...}): void
  get(path: Array<string | number> | string): AbstractControl | null
  getError(errorCode: string, path?: string[]): any
  hasError(errorCode: string, path?: string[]): boolean
}
    

Description

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 status values 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.

When instantiating a FormGroup, pass in a collection of child controls as the first argument. The key for each child registers the name for the control.

Constructor

Creates a new FormGroup instance.

constructor(controls: { [key: string]: AbstractControl; }, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null)
      
      constructor(controls: {
    [key: string]: AbstractControl;
}, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null)
    

Parameters

controls

A collection of child controls. The key for each child is the name under which it is registered.

validatorOrOpts

A synchronous validator function, or an array of such functions, or an AbstractControlOptions object that contains validation functions and a validation trigger.

Optional. Default is undefined.

asyncValidator

A single async validator or array of async validator functions

Optional. Default is undefined.

Properties

Property Description
controls: { [key: string]: AbstractControl; }

A collection of child controls. The key for each child is the name under which it is registered.

Declared in constructor.

Methods

Registers a control with the group's list of controls.

registerControl(name: string, control: AbstractControl): AbstractControl
      
      registerControl(name: string, control: AbstractControl): AbstractControl
    

Parameters

name

The control name to register in the collection

control

Provides the control for the given name

Returns

AbstractControl

This method does not update the value or validity of the control. Use addControl instead.

Add a control to this group.

addControl(name: string, control: AbstractControl): void
      
      addControl(name: string, control: AbstractControl): void
    

Parameters

name

The control name to add to the collection

control

Provides the control for the given name

Returns

void

This method also updates the value and validity of the control.

Remove a control from this group.

removeControl(name: string): void
      
      removeControl(name: string): void
    

Parameters

name

The control name to remove from the collection

Returns

void

Replace an existing control.

setControl(name: string, control: AbstractControl): void
      
      setControl(name: string, control: AbstractControl): void
    

Parameters

name

The control name to replace in the collection

control

Provides the control for the given name

Returns

void

Check whether there is an enabled control with the given name in the group.

contains(controlName: string): boolean
      
      contains(controlName: string): boolean
    

Parameters

controlName

Type: string.

Returns

boolean: false for disabled controls, true otherwise.

Reports false for disabled controls. If you'd like to check for existence in the group only, use get instead.

Sets the value of the FormGroup. It accepts an object that matches the structure of the group, with control names as keys.

setValue(value: { [key: string]: any; }, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void
      
      setValue(value: {
    [key: string]: any;
}, options: {
    onlySelf?: boolean;
    emitEvent?: boolean;
} = {}): void
    

Parameters

value

The new value for the control that matches the structure of the group.

options

Configuration options that determine how the control propagates changes and emits events after the value changes. The configuration options are passed to the updateValueAndValidity method.

  • onlySelf: When true, each change only affects this control, and not its parent. Default is false.
  • emitEvent: When true or not supplied (the default), both the statusChanges and valueChanges observables emit events with the latest status and value when the control value is updated. When false, no events are emitted.

Optional. Default is {}.

Returns

void

Throws

Error When strict checks fail, such as setting the value of a control that doesn't exist or if you excluding the value of a control.

Set the complete value for the form group

const form = new FormGroup({ first: new FormControl(), last: new FormControl() }); console.log(form.value); // {first: null, last: null} form.setValue({first: 'Nancy', last: 'Drew'}); console.log(form.value); // {first: 'Nancy', last: 'Drew'}
      
      const form = new FormGroup({
  first: new FormControl(),
  last: new FormControl()
});

console.log(form.value);   // {first: null, last: null}

form.setValue({first: 'Nancy', last: 'Drew'});
console.log(form.value);   // {first: 'Nancy', last: 'Drew'}
    

Patches the value of the FormGroup. It accepts an object with control names as keys, and does its best to match the values to the correct controls in the group.

patchValue(value: { [key: string]: any; }, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void
      
      patchValue(value: {
    [key: string]: any;
}, options: {
    onlySelf?: boolean;
    emitEvent?: boolean;
} = {}): void
    

Parameters

value

The object that matches the structure of the group.

options

Configuration options that determine how the control propagates changes and emits events after the value is patched.

  • onlySelf: When true, each change only affects this control and not its parent. Default is true.
  • emitEvent: When true or not supplied (the default), both the statusChanges and valueChanges observables emit events with the latest status and value when the control value is updated. When false, no events are emitted. The configuration options are passed to the updateValueAndValidity method.

Optional. Default is {}.

Returns

void

It accepts both super-sets and sub-sets of the group without throwing an error.

Patch the value for a form group

const form = new FormGroup({ first: new FormControl(), last: new FormControl() }); console.log(form.value); // {first: null, last: null} form.patchValue({first: 'Nancy'}); console.log(form.value); // {first: 'Nancy', last: null}
      
      const form = new FormGroup({
   first: new FormControl(),
   last: new FormControl()
});
console.log(form.value);   // {first: null, last: null}

form.patchValue({first: 'Nancy'});
console.log(form.value);   // {first: 'Nancy', last: null}
    

Resets the FormGroup, marks all descendants are marked pristine and untouched, and the value of all descendants to null.

reset(value: any = {}, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void
      
      reset(value: any = {}, options: {
    onlySelf?: boolean;
    emitEvent?: boolean;
} = {}): void
    

Parameters

value

Type: any.

Optional. Default is {}.

options

Configuration options that determine how the control propagates changes and emits events when the group is reset.

  • onlySelf: When true, each change only affects this control, and not its parent. Default is false.
  • emitEvent: When true or not supplied (the default), both the statusChanges and valueChanges observables emit events with the latest status and value when the control is reset. When false, no events are emitted. The configuration options are passed to the updateValueAndValidity method.

Optional. Default is {}.

Returns

void

You reset to a specific form state by passing in a map of states that matches the structure of your form, with control names as keys. The state is a standalone value or a form state object with both a value and a disabled status.

Reset the form group values

const form = new FormGroup({ first: new FormControl('first name'), last: new FormControl('last name') }); console.log(form.value); // {first: 'first name', last: 'last name'} form.reset({ first: 'name', last: 'last name' }); console.log(form.value); // {first: 'name', last: 'last name'}
      
      const form = new FormGroup({
  first: new FormControl('first name'),
  last: new FormControl('last name')
});

console.log(form.value);  // {first: 'first name', last: 'last name'}

form.reset({ first: 'name', last: 'last name' });

console.log(form.value);  // {first: 'name', last: 'last name'}
    

Reset the form group values and disabled status

const form = new FormGroup({ first: new FormControl('first name'), last: new FormControl('last name') }); form.reset({ first: {value: 'name', disabled: true}, last: 'last' }); console.log(this.form.value); // {first: 'name', last: 'last name'} console.log(this.form.get('first').status); // 'DISABLED'
      
      const form = new FormGroup({
  first: new FormControl('first name'),
  last: new FormControl('last name')
});

form.reset({
  first: {value: 'name', disabled: true},
  last: 'last'
});

console.log(this.form.value);  // {first: 'name', last: 'last name'}
console.log(this.form.get('first').status);  // 'DISABLED'
    

The aggregate value of the FormGroup, including any disabled controls.

getRawValue(): any
      
      getRawValue(): any
    

Parameters

There are no parameters.

Returns

any

Retrieves all values regardless of disabled status. The value property is the best way to get the value of the group, because it excludes disabled controls in the FormGroup.

Usage notes

Create a form group with 2 controls

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'
      
      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'
    

Create a form group with a group-level validator

You 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.

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}; }
      
      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};
}
    

Like FormControl instances, you choose to pass in validators and async validators as part of an options object.

const form = new FormGroup({ password: new FormControl('') passwordConfirm: new FormControl('') }, { validators: passwordMatchValidator, asyncValidators: otherValidator });
      
      const form = new FormGroup({
  password: new FormControl('')
  passwordConfirm: new FormControl('')
}, { validators: passwordMatchValidator, asyncValidators: otherValidator });
    

Set the updateOn property for all controls in a form group

The options object is used to set a default value for each child control's updateOn property. If you set updateOn to 'blur' at the group level, all child controls default to 'blur', unless the child has explicitly specified a different updateOn value.

const c = new FormGroup({ one: new FormControl() }, { updateOn: 'blur' });
      
      const c = new FormGroup({
  one: new FormControl()
}, { updateOn: 'blur' });