填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

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, 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

  // 繼承自 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(newValidator: ValidatorFn | ValidatorFn[]): void
  setAsyncValidators(newValidator: AsyncValidatorFn | AsyncValidatorFn[]): void
  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
}
    

說明

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.

Further information available in the Usage Notes...

建構函式

建立一個新的 FormArray 實例

Creates a new FormArray instance.

      
      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
    
引數
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, options: { emitEvent?: boolean; } = {}): void
    
引數
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.
可選. 預設值是 `{}`.
返回值

void

在陣列中的指定 index 處插入一個新的 AbstractControl

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

      
      insert(index: number, control: AbstractControl, options: { emitEvent?: boolean; } = {}): void
    
引數
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.
可選. 預設值是 `{}`.
返回值

void

移除位於陣列中的指定 index 處的控制元件。

Remove the control at the given index in the array.

      
      removeAt(index: number, options: { emitEvent?: boolean; } = {}): void
    
引數
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.
可選. 預設值是 `{}`.
返回值

void

替換現有控制元件。

Replace an existing control.

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

要替換的控制元件在陣列中的索引

Index in the array to replace the control

control AbstractControl

要用來替換現有控制元件的 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.
可選. 預設值是 `{}`.
返回值

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

修補此 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
    
引數
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]
    

重置這個 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
    
引數
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']
    
重置表單陣列中的各個值和第一個控制元件的禁用狀態
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'
    

這個 FormArray 的聚合值,包括所有已禁用的控制元件。

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

      
      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.

移除 FormArray 的所有控制元件。

Remove all controls in the FormArray.

      
      clear(options: { emitEvent?: boolean; } = {}): void
    
引數
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.
可選. 預設值是 `{}`.
返回值

void

使用說明

從 FormArray 刪除所有元素
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);
}
    

使用說明

建立表單控制元件的陣列

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

為表單陣列中的所有控制元件設定 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'});
    

從表單陣列中新增或刪除控制元件

Adding or removing controls from a form array

要改變陣列中的控制元件列表,可以使用 FormArray 本身的 pushinsertremoveAtclear 方法。這些方法能確保表單陣列正確的追蹤這些子控制元件。 不要直接修改實例化 FormArray 時傳入的那個 AbstractControl 陣列,否則會導致奇怪的、非預期的行為,比如破壞變更檢測機制。

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.