On this page
FormArray
class
npm Package | @angular/forms |
---|---|
Module | import { FormArray } from '@angular/forms'; |
Source | forms/src/model.ts |
Overview
class FormArray extends AbstractControl {
constructor(controls: AbstractControl[], validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null)
controls: AbstractControl[]
at(index: number): AbstractControl
push(control: AbstractControl): void
insert(index: number, control: AbstractControl): void
removeAt(index: number): void
setControl(index: number, control: AbstractControl): void
get length: number
setValue(value: any[], options: {...}): void
patchValue(value: any[], options: {...}): void
reset(value: any = [], options: {...}): void
getRawValue(): any[]
// inherited from forms/AbstractControl
get value: any
validator: ValidatorFn | null
asyncValidator: AsyncValidatorFn | null
get parent: FormGroup | FormArray
get status: string
get valid: boolean
get invalid: boolean
get pending: boolean
get disabled: boolean
get enabled: boolean
get errors: ValidationErrors | null
get pristine: boolean
get dirty: boolean
get touched: boolean
get untouched: boolean
get valueChanges: Observable<any>
get statusChanges: Observable<any>
get updateOn: FormHooks
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
setValue(value: any, options?: Object): void
patchValue(value: any, options?: Object): void
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
get root: AbstractControl
}
How To Use
When instantiating a FormArray
, pass in an array of child controls as the first argument.
Example
const arr = new FormArray([
new FormControl('Nancy', Validators.minLength(2)),
new FormControl('Drew'),
]);
console.log(arr.value); // ['Nancy', 'Drew']
console.log(arr.status); // 'VALID'
You can also 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 can be 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});
The options object can also be 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 will default to 'blur', unless the child has explicitly specified a different updateOn
value.
const c = new FormArray([
new FormControl()
], {updateOn: 'blur'});
Adding or removing controls
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 AbstractControl
s used to instantiate the FormArray
directly, as that will result in strange and unexpected behavior such as broken change detection.
- npm package:
@angular/forms
Constructor
constructor(controls: AbstractControl[], validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null)
Members
controls: AbstractControl[]
at(index: number): AbstractControl
Get the AbstractControl
at the given index
in the array.
push(control: AbstractControl): void
Insert a new AbstractControl
at the end of the array.
insert(index: number, control: AbstractControl): void
Insert a new AbstractControl
at the given index
in the array.
removeAt(index: number): void
Remove the control at the given index
in the array.
setControl(index: number, control: AbstractControl): void
Replace an existing control.
get length: number
Length of the control array.
setValue(value: any[], options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void
Sets the value of the FormArray
. It accepts an array that matches the structure of the control.
This method performs strict checks, so it will throw 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.
Example
const arr = new FormArray([
new FormControl(),
new FormControl()
]);
console.log(arr.value); // [null, null]
arr.setValue(['Nancy', 'Drew']);
console.log(arr.value); // ['Nancy', 'Drew']
patchValue(value: any[], options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void
Patches the value of the FormArray
. It accepts an array that matches the structure of the control, and will do its best to match the values to the correct controls in the group.
It accepts both super-sets and sub-sets of the array without throwing an error.
Example
const arr = new FormArray([
new FormControl(),
new FormControl()
]);
console.log(arr.value); // [null, null]
arr.patchValue(['Nancy']);
console.log(arr.value); // ['Nancy', null]
reset(value: any = [], options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void
Resets the FormArray
. This means by default:
- The array and all descendants are marked
pristine
- The array and all descendants are marked
untouched
- The value of all descendants will be null or null maps
You can also reset to a specific form state by passing in an array of states that matches the structure of the control. The state can be a standalone value or a form state object with both a value and a disabled status.
Example
this.arr.reset(['name', 'last name']);
console.log(this.arr.value); // ['name', 'last name']
- OR -
this.arr.reset([
{value: 'name', disabled: true},
'last'
]);
console.log(this.arr.value); // ['name', 'last name']
console.log(this.arr.get(0).status); // 'DISABLED'
getRawValue(): any[]
The aggregate value of the array, including any disabled controls.
If you'd like to include all values regardless of disabled status, use this method. Otherwise, the value
property is the best way to get the value of the array.
© 2010–2018 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://v5.angular.io/api/forms/FormArray