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

FormArray

Tracks the value and validity state of an array of FormControl, FormGroup or FormArray instances.

See more...

class FormArray extends AbstractControl { constructor(controls: AbstractControl[], validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null) controls: AbstractControl[] length: number at(index: number): AbstractControl push(control: AbstractControl): void insert(index: number, control: AbstractControl): void removeAt(index: number): void setControl(index: number, control: AbstractControl): void setValue(value: any[], options: {...}): void patchValue(value: any[], 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 FormArray extends AbstractControl {
  constructor(controls: AbstractControl[], validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null)
  controls: AbstractControl[]
  length: number
  at(index: number): AbstractControl
  push(control: AbstractControl): void
  insert(index: number, control: AbstractControl): void
  removeAt(index: number): void
  setControl(index: number, control: AbstractControl): void
  setValue(value: any[], options: {...}): void
  patchValue(value: any[], 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 FormArray aggregates the values of each child FormControl into an array. It calculates its status by reducing the status values of its children. For example, if one of the controls in a FormArray is invalid, the entire array becomes invalid.

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

Constructor

Creates a new FormArray instance.

constructor(controls: AbstractControl[], validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null)
      
      constructor(controls: AbstractControl[], validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null)
    

Parameters

controls

An array of child controls. Each child control is given an index where 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: AbstractControl[]

An array of child controls. Each child control is given an index where it is registered.

Declared in constructor.
length: number Read-only.

Length of the control array.

Methods

Get the AbstractControl at the given index in the array.

at(index: number): AbstractControl
      
      at(index: number): AbstractControl
    

Parameters

index

Index in the array to retrieve the control

Returns

AbstractControl

Insert a new AbstractControl at the end of the array.

push(control: AbstractControl): void
      
      push(control: AbstractControl): void
    

Parameters

control

Form control to be inserted

Returns

void

Insert a new AbstractControl at the given index in the array.

insert(index: number, control: AbstractControl): void
      
      insert(index: number, control: AbstractControl): void
    

Parameters

index

Index in the array to insert the control

control

Form control to be inserted

Returns

void

Remove the control at the given index in the array.

removeAt(index: number): void
      
      removeAt(index: number): void
    

Parameters

index

Index in the array to remove the control

Returns

void

Replace an existing control.

setControl(index: number, control: AbstractControl): void
      
      setControl(index: number, control: AbstractControl): void
    

Parameters

index

Index in the array to replace the control

control

The AbstractControl control to replace the existing control

Returns

void

Sets the value of the FormArray. It accepts an array that matches the structure of the control.

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

Parameters

value

Array of values for the controls

options

Configure options that determine how the control propagates changes and emits events after the value changes

  • 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. The configuration options are passed to the updateValueAndValidity method.

Optional. Default is {}.

Returns

void

This method performs strict checks, and throws an error if you try to set the value of a control that doesn't exist or if you exclude the value of a control.

Set the values for the controls in the form array

const arr = new FormArray([ new FormControl(), new FormControl() ]); console.log(arr.value); // [null, null] arr.setValue(['Nancy', 'Drew']); console.log(arr.value); // ['Nancy', 'Drew']
      
      const arr = new FormArray([
  new FormControl(),
  new FormControl()
]);
console.log(arr.value);   // [null, null]

arr.setValue(['Nancy', 'Drew']);
console.log(arr.value);   // ['Nancy', 'Drew']
    

Patches the value of the FormArray. It accepts an array that matches the structure of the control, and does its best to match the values to the correct controls in the group.

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

Parameters

value

Array of latest values for the controls

options

Configure options that determine how the control propagates changes and emits events after the value changes

  • 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. The configuration options are passed to the updateValueAndValidity method.

Optional. Default is {}.

Returns

void

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

Patch the values for controls in a form array

const arr = new FormArray([ new FormControl(), new FormControl() ]); console.log(arr.value); // [null, null] arr.patchValue(['Nancy']); console.log(arr.value); // ['Nancy', null]
      
      const arr = new FormArray([
   new FormControl(),
   new FormControl()
]);
console.log(arr.value);   // [null, null]

arr.patchValue(['Nancy']);
console.log(arr.value);   // ['Nancy', null]
    

Resets the FormArray and all descendants are marked pristine and untouched, and the value of all descendants to null or null maps.

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

Parameters

value

Array of values for the controls

Optional. Default is [].

options

Configure options that determine how the control propagates changes and emits events after the value changes

  • 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 an array of states that matches the structure of the control. The state is a standalone value or a form state object with both a value and a disabled status.

Reset the values in a form array

const arr = new FormArray([ new FormControl(), new FormControl() ]); arr.reset(['name', 'last name']); console.log(this.arr.value); // ['name', 'last name']
      
      const arr = new FormArray([
   new FormControl(),
   new FormControl()
]);
arr.reset(['name', 'last name']);

console.log(this.arr.value);  // ['name', 'last name']
    

Reset the values in a form array and the disabled status for the first control

this.arr.reset([ {value: 'name', disabled: true}, 'last' ]); console.log(this.arr.value); // ['name', 'last name'] console.log(this.arr.get(0).status); // 'DISABLED'
      
      this.arr.reset([
  {value: 'name', disabled: true},
  'last'
]);

console.log(this.arr.value);  // ['name', 'last name']
console.log(this.arr.get(0).status);  // 'DISABLED'
    

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

getRawValue(): any[]
      
      getRawValue(): any[]
    

Parameters

There are no parameters.

Returns

any[]

Reports all values regardless of disabled status. For enabled controls only, the value property is the best way to get the value of the array.

Usage notes

Create an array of form controls

const arr = new FormArray([ new FormControl('Nancy', Validators.minLength(2)), new FormControl('Drew'), ]); console.log(arr.value); // ['Nancy', 'Drew'] console.log(arr.status); // 'VALID'
      
      const arr = new FormArray([
  new FormControl('Nancy', Validators.minLength(2)),
  new FormControl('Drew'),
]);

console.log(arr.value);   // ['Nancy', 'Drew']
console.log(arr.status);  // 'VALID'
    

Create a form array with array-level validators

You include array-level validators and async validators. These come in handy when you want to perform validation that considers the value of more than one child control.

The two types of validators are passed in separately as the second and third arg respectively, or together as part of an options object.

const arr = new FormArray([ new FormControl('Nancy'), new FormControl('Drew') ], {validators: myValidator, asyncValidators: myAsyncValidator});
      
      const arr = new FormArray([
  new FormControl('Nancy'),
  new FormControl('Drew')
], {validators: myValidator, asyncValidators: myAsyncValidator});
    

Set the updateOn property for all controls in a form array

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 array level, all child controls default to 'blur', unless the child has explicitly specified a different updateOn value.

const arr = new FormArray([ new FormControl() ], {updateOn: 'blur'});
      
      const arr = new FormArray([
   new FormControl()
], {updateOn: 'blur'});
    

Adding or removing controls from a form array

To change the controls in the array, use the push, insert, or removeAt methods in FormArray itself. These methods ensure the controls are properly tracked in the form's hierarchy. Do not modify the array of AbstractControls used to instantiate the FormArray directly, as that result in strange and unexpected behavior such as broken change detection.