FormArray

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

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

查看"说明"...

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): void insert(index: number, control: AbstractControl): void removeAt(index: number): void setControl(index: number, control: AbstractControl): 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[] // 继承自 forms/AbstractControl constructor(validator: ValidatorFn, asyncValidator: AsyncValidatorFn) 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[]): void setAsyncValidators(newValidator: AsyncValidatorFn | AsyncValidatorFn[]): void clearValidators(): void clearAsyncValidators(): void markAsTouched(opts: { onlySelf?: boolean; } = {}): 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[]): any hasError(errorCode: string, path?: string[]): boolean }
      
      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): void
  insert(index: number, control: AbstractControl): void
  removeAt(index: number): void
  setControl(index: number, control: AbstractControl): 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[]

  // 继承自 forms/AbstractControl
  constructor(validator: ValidatorFn, asyncValidator: AsyncValidatorFn)
  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[]): void
  setAsyncValidators(newValidator: AsyncValidatorFn | AsyncValidatorFn[]): void
  clearValidators(): void
  clearAsyncValidators(): void
  markAsTouched(opts: { onlySelf?: boolean; } = {}): 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[]): any
  hasError(errorCode: string, path?: string[]): boolean
}
    

说明

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

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 是 Angular 表单中定义的三个基本构造块之一,就像 FormControlFormGroup 一样。

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

构造函数

创建一个新的 FormArray 实例

Creates a new FormArray instance.

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

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

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

validatorOrOpts ValidatorFn | AbstractControlOptions | ValidatorFn[]

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

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

可选. 默认值是 undefined.

asyncValidator AsyncValidatorFn | AsyncValidatorFn[]

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

A single async validator or array of async validator functions

可选. 默认值是 undefined.

属性

属性说明
controls: AbstractControl[]

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

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

声明于构造函数中
length: number 只读

控件数组的长度。

Length of the control array.

方法

获取数组中指定 index 处的 AbstractControl

Get the AbstractControl at the given index in the array.

at(index: number): AbstractControl
      
      at(index: number): AbstractControl
    
参数
index number

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

Index in the array to retrieve the control

返回值

AbstractControl

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

Insert a new AbstractControl at the end of the array.

push(control: AbstractControl): void
      
      push(control: AbstractControl): void
    
参数
control AbstractControl

要插入的表单控件

Form control to be inserted

返回值

void

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

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

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

要插入该控件的索引序号

Index in the array to insert the control

control AbstractControl

要插入的表单控件

Form control to be inserted

返回值

void

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

Remove the control at the given index in the array.

removeAt(index: number): void
      
      removeAt(index: number): void
    
参数
index number

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

Index in the array to remove the control

返回值

void

替换现有控件。

Replace an existing control.

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

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

Index in the array to replace the control

control AbstractControl

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

The AbstractControl control to replace the existing control

返回值

void

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

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
    
参数
value any[]

要传给这些控件的值的数组

Array of values for the controls

options object

当值变化时,此配置项会决定该控件会如何传播变更以及发出事件。

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

  • onlySelf::如果为 true,则每个变更仅仅影响当前控件,而不会影响父控件。默认为 false

    onlySelf: When true, each change only affects this control, and not its parent. Default is false.

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

    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.

可选. 默认值是 {}.

返回值

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

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

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
    
参数
value any[]

由各个控件最近的值组成的数组

Array of latest values for the controls

options object

在修补了该值之后,此配置项会决定控件如何传播变更以及发出事件。

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

  • onlySelf::如果为 true,则每个变更仅仅影响当前控件,而不会影响父控件。默认为 false

    onlySelf: When true, each change only affects this control, and not its parent. Default is false.

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

    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.

可选. 默认值是 {}.

返回值

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]
    

重置这个 FormArray,把它的各级子控件都标记为 pristineuntouched,并把它们的值都设置为 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
    
参数
value any

各个控件值的数组

Array of values for the controls

可选. 默认值是 [].

options object

当值变化时,此配置项会决定该控件如何传播变更以及发出事件。

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

  • onlySelf::如果为 true,则每个变更仅仅影响当前控件,而不会影响父控件。默认为 false

    onlySelf: When true, each change only affects this control, and not its parent. Default is false.

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

    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.

可选. 默认值是 {}.

返回值

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'
    

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

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

getRawValue(): any[]
      
      getRawValue(): any[]
    
参数

没有参数。

返回值

any[]

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

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.

使用说明

创建表单控件的数组

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

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

Set the updateOn property for all controls in a form array

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

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

从表单数组中添加或删除控件

Adding or removing controls from a form array

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

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.