W3cubDocs

/Angular 12

FormArray

class final

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 | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[])
  controls: AbstractControl[]
  length: number
  at(index: number): AbstractControl
  push(control: AbstractControl, options: { emitEvent?: boolean; } = {}): void
  insert(index: number, control: AbstractControl, options: { emitEvent?: boolean; } = {}): void
  removeAt(index: number, options: { emitEvent?: boolean; } = {}): void
  setControl(index: number, control: AbstractControl, options: { emitEvent?: boolean; } = {}): void
  setValue(value: any[], options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void
  patchValue(value: any[], options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void
  reset(value: any = [], options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void
  getRawValue(): any[]
  clear(options: { emitEvent?: boolean; } = {}): void
  _syncPendingControls(): boolean
  _forEachChild(cb: Function): void
  _updateValue(): void
  _anyControls(condition: Function): boolean
  _allControlsDisabled(): boolean

  // inherited from forms/AbstractControl
  constructor(validators: ValidatorFn | ValidatorFn[], asyncValidators: AsyncValidatorFn | AsyncValidatorFn[])
  value: any
  validator: ValidatorFn | null
  asyncValidator: AsyncValidatorFn | null
  parent: FormGroup | FormArray | null
  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(validators: ValidatorFn | ValidatorFn[]): void
  setAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void
  addValidators(validators: ValidatorFn | ValidatorFn[]): void
  addAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void
  removeValidators(validators: ValidatorFn | ValidatorFn[]): void
  removeAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void
  hasValidator(validator: ValidatorFn): boolean
  hasAsyncValidator(validator: AsyncValidatorFn): boolean
  clearValidators(): void
  clearAsyncValidators(): void
  markAsTouched(opts: { onlySelf?: boolean; } = {}): void
  markAllAsTouched(): void
  markAsUntouched(opts: { onlySelf?: boolean; } = {}): void
  markAsDirty(opts: { onlySelf?: boolean; } = {}): void
  markAsPristine(opts: { onlySelf?: boolean; } = {}): void
  markAsPending(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void
  disable(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void
  enable(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): 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: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void
  setErrors(errors: ValidationErrors, opts: { emitEvent?: boolean; } = {}): void
  get(path: string | (string | number)[]): AbstractControl | null
  getError(errorCode: string, path?: string | (string | number)[]): any
  hasError(errorCode: string, path?: string | (string | number)[]): 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.

Further information is available in the Usage Notes...

Constructor

Creates a new FormArray instance.

This class is "final" and should not be extended. See the public API notes.

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

Parameters
controls AbstractControl[]

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

validatorOrOpts ValidatorFn | AbstractControlOptions | ValidatorFn[]

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 AsyncValidatorFn | AsyncValidatorFn[]

A single async validator or array of async validator functions

Optional. Default is undefined.

Properties

Property Description
controls: AbstractControl[] Declared in Constructor

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

length: number Read-Only

Length of the control array.

Methods

Get the AbstractControl at the given index in the array.

at(index: number): AbstractControl

Parameters
index number

Index in the array to retrieve the control

Returns

AbstractControl

Insert a new AbstractControl at the end of the array.

push(control: AbstractControl, options: { emitEvent?: boolean; } = {}): void

Parameters
control AbstractControl

Form control to be inserted

options object

Specifies whether this FormArray instance should emit events after a new control is added.

  • 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 inserted. When false, no events are emitted.

Optional. Default is {}.

Returns

void

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

insert(index: number, control: AbstractControl, options: { emitEvent?: boolean; } = {}): void

Parameters
index number

Index in the array to insert the control

control AbstractControl

Form control to be inserted

options object

Specifies whether this FormArray instance should emit events after a new control is inserted.

  • 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 inserted. When false, no events are emitted.

Optional. Default is {}.

Returns

void

Remove the control at the given index in the array.

removeAt(index: number, options: { emitEvent?: boolean; } = {}): void

Parameters
index number

Index in the array to remove the control

options object

Specifies whether this FormArray instance should emit events after a control is removed.

  • 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 removed. When false, no events are emitted.

Optional. Default is {}.

Returns

void

Replace an existing control.

setControl(index: number, control: AbstractControl, options: { emitEvent?: boolean; } = {}): void

Parameters
index number

Index in the array to replace the control

control AbstractControl

The AbstractControl control to replace the existing control

options object

Specifies whether this FormArray instance should emit events after an existing control is replaced with a new one.

  • 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 replaced with a new one. When false, no events are emitted.

Optional. Default is {}.

Returns

void

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

Parameters
value any[]
options object

Optional. Default is {}.

Returns

void

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

Parameters
value any[]
options object

Optional. Default is {}.

Returns

void

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

Parameters
value any

Optional. Default is [].

options object

Optional. Default is {}.

Returns

void

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

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.

Remove all controls in the FormArray.

clear(options: { emitEvent?: boolean; } = {}): void

Parameters
options object

Specifies whether this FormArray instance should emit events after all controls are removed.

  • emitEvent: When true or not supplied (the default), both the statusChanges and valueChanges observables emit events with the latest status and value when all controls in this FormArray instance are removed. When false, no events are emitted.

Optional. Default is {}.

Returns

void

Usage Notes

Remove all elements from a FormArray
const arr = new FormArray([
   new FormControl(),
   new FormControl()
]);
console.log(arr.length);  // 2

arr.clear();
console.log(arr.length);  // 0

It's a simpler and more efficient alternative to removing all elements one by one:

const arr = new FormArray([
   new FormControl(),
   new FormControl()
]);

while (arr.length) {
   arr.removeAt(0);
}

_syncPendingControls(): boolean

Parameters

There are no parameters.

Returns

boolean

_forEachChild(cb: Function): void

Parameters
cb Function
Returns

void

_updateValue(): void

Parameters

There are no parameters.

Returns

void

_anyControls(condition: Function): boolean

Parameters
condition Function
Returns

boolean

_allControlsDisabled(): boolean

Parameters

There are no parameters.

Returns

boolean

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'

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

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

Adding or removing controls from a form array

To change the controls in the array, use the push, insert, removeAt or clear 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.

© 2010–2021 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://v12.angular.io/api/forms/FormArray