FormArray

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

跟踪一个控件数组的值和有效性状态,控件可以是 FormControlFormGroupFormArray 的实例。

class FormArray extends AbstractControl { constructor(controls: AbstractControl[], validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null) controls: AbstractControl[] get 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[] // 继承自 forms/AbstractControl constructor(validator: ValidatorFn | null, asyncValidator: AsyncValidatorFn | null) 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 get 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 }

说明

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 聚合了数组中每个表单控件的值。 它还会根据其所有子控件的状态总结出自己的状态。比如,如果 FromArray 中的任何一个控件是无效的,那么整个数组也会变成无效的。

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

FormArray 是 Angular 表单中定义的三个基本构造块之一,就像 FormControlFormGroup 一样。

构造函数

Creates a new FormArray instance.

创建一个新的 FormArray 实例

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

参数

controls

An array of child controls. Each child control is given an index wheh 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.

一个同步验证器函数或其数组,或者一个包含验证函数和验证触发器的 AbstractControlOptions 对象。

可选. 默认值是 undefined.

asyncValidator

A single async validator or array of async validator functions

单个的异步验证器函数或其数组。

可选. 默认值是 undefined.

属性

属性名类型说明
controls

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

一个子控件数组。在注册后,每个子控件都会有一个指定的索引。

声明于构造函数中
length只读

Length of the control array.

控件数组的长度。

方法

Get the AbstractControl at the given index in the array.

获取数组中指定 index 处的 AbstractControl

at(index: number): AbstractControl

参数

index

Index in the array to retrieve the control

要获取的控件在数组中的索引

返回值

AbstractControl

Insert a new AbstractControl at the end of the array.

在数组的末尾插入一个新的 AbstractControl

push(control: AbstractControl): void

参数

control

Form control to be inserted

要插入的表单控件

返回值

void

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

在数组中的指定 index 处插入一个新的 AbstractControl

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

参数

index

Index in the array to insert the control

要插入该控件的索引序号

control

Form control to be inserted

要插入的表单控件

返回值

void

Remove the control at the given index in the array.

移除位于数组中的指定 index 处的控件。

removeAt(index: number): void

参数

index

Index in the array to remove the control

要移除的控件在数组中的索引

返回值

void

Replace an existing control.

替换现有控件。

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

参数

index

Index in the array to replace the control

要替换的控件在数组中的索引

control

The AbstractControl control to replace the existing control

要用来替换现有控件的 AbstractControl 控件

返回值

void

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

设置此 FormArray 的值。它接受一个与控件结构相匹配的数组。

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

参数

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.

    onlySelf::如果为 true,则每个变更仅仅影响当前控件,而不会影响父控件。默认为 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.

    emitEvent:如果为 true 或未提供(默认),则当控件值发生变化时,statusChangesvalueChanges 这两个 Observable 分别会以最近的状态和值发出事件。 如果为 false 则不发出事件。 该配置项会被传给 updateValueAndValidity 方法。

可选. 默认值是 {}.

返回值

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

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.

修补此 FormArray 的值。它接受一个与该控件的结构相匹配的数组,并尽量把它们的值匹配到组中正确的控件上。

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

参数

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.

    onlySelf::如果为 true,则每个变更仅仅影响当前控件,而不会影响父控件。默认为 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.

    emitEvent:如果为 true 或未提供(默认),则当控件值发生变化时,statusChangesvalueChanges 这两个 Observable 分别会以最近的状态和值发出事件。 如果为 false 则不发出事件。 该配置项会被传给 updateValueAndValidity 方法。

可选. 默认值是 {}.

返回值

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]

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

重置这个 FormArray,把它的各级子控件都标记为 pristineuntouched,并把它们的值都设置为 null

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

参数

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.

    onlySelf::如果为 true,则每个变更仅仅影响当前控件,而不会影响父控件。默认为 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.

    emitEvent:如果为 true 或未提供(默认),则当控件值发生变化时,statusChangesvalueChanges 这两个 Observable 分别会以最近的状态和值发出事件。 如果为 false 则不发出事件。 该配置项会被传给 updateValueAndValidity 方法。

可选. 默认值是 {}.

返回值

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

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'

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

这个 FormArray 的聚合值,包括所有已禁用的控件。

getRawValue(): any[]

参数

没有参数。

返回值

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.

获取所有控件的值而不管其禁用状态。 如果只想获取已启用的控件的值,则最好使用 value 属性来获取此数组的值。

使用说明

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

为表单数组中的所有控件设置 updateOn 属性

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.

该配置对象可以为每个子控件的 updateOn 属性设置默认值。 如果在数组级把 updateOn 设置为 'blur',则所有子控件的默认值也是 'blur',除非这个子控件显式的指定了另一个 updateOn 值。

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.

要改变数组中的控件列表,可以使用 FormArray 本身的 pushinsertremoveAt 方法。这些方法能确保表单数组正确的跟踪这些子控件。 不要直接修改实例化 FormArray 时传入的那个 AbstractControl 数组,否则会导致奇怪的、非预期的行为,比如破坏变更检测机制。