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

FormGroup

追蹤一組 FormControl 實例的值和有效性狀態。

Tracks the value and validity state of a group of FormControl instances.

檢視"說明"...

      
      class FormGroup extends AbstractControl {
  constructor(controls: { [key: string]: AbstractControl; }, validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[])
  controls: {...}
  registerControl(name: string, control: AbstractControl): AbstractControl
  addControl(name: string, control: AbstractControl, options: { emitEvent?: boolean; } = {}): void
  removeControl(name: string, options: { emitEvent?: boolean; } = {}): void
  setControl(name: string, control: AbstractControl, options: { emitEvent?: boolean; } = {}): void
  contains(controlName: string): boolean
  setValue(value: { [key: string]: any; }, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void
  patchValue(value: { [key: string]: any; }, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void
  reset(value: any = {}, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void
  getRawValue(): any

  // 繼承自 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
}
    

說明

FormGroup 把每個子 FormControl 的值聚合進一個物件,它的 key 是每個控制元件的名字。 它透過歸集其子控制元件的狀態值來計算出自己的狀態。 比如,如果組中的任何一個控制元件是無效的,那麼整個組就是無效的。

A FormGroup aggregates the values of each child FormControl into one object, with each control name as the key. It calculates its status by reducing the status values of its children. For example, if one of the controls in a group is invalid, the entire group becomes invalid.

FormGroup 是 Angular 中用來定義表單的三大基本構成要素之一,就像 FormControlFormArray 一樣。

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

當實例化 FormGroup 時,在第一個引數中傳入一組子控制元件。每個子控制元件會用控制元件名把自己註冊進去。

When instantiating a FormGroup, pass in a collection of child controls as the first argument. The key for each child registers the name for the control.

Further information available in the Usage Notes...

建構函式

建立一個新的 FormGroup 實例

Creates a new FormGroup instance.

      
      constructor(controls: { [key: string]: AbstractControl; }, validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[])
    
引數
controls object

一組子控制元件。每個子控制元件的名字就是它註冊時用的 key

A collection of child controls. The key for each child is the name under which 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: { [key: string]: AbstractControl; }宣告在建構函式中

一組子控制元件。每個子控制元件的名字就是它註冊時用的 key

A collection of child controls. The key for each child is the name under which it is registered.

方法

向組內的控制元件列表中註冊一個控制元件。

Registers a control with the group's list of controls.

      
      registerControl(name: string, control: AbstractControl): AbstractControl
    
引數
name string

註冊到集合中的控制元件名

The control name to register in the collection

control AbstractControl

提供這個名字對應的控制元件

Provides the control for the given name

返回值

AbstractControl

該方法不會更新控制元件的值或其有效性。 使用 addControl 代替。

This method does not update the value or validity of the control. Use addControl instead.

往組中新增一個控制元件。

Add a control to this group.

      
      addControl(name: string, control: AbstractControl, options: { emitEvent?: boolean; } = {}): void
    
引數
name string

要註冊到集合中的控制元件名

The control name to add to the collection

control AbstractControl

提供與該控制元件名對應的控制元件。

Provides the control for the given name

options object

Specifies whether this FormGroup 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 added. When false, no events are emitted.
可選. 預設值是 `{}`.
返回值

void

該方法還會更新本空間的值和有效性。

This method also updates the value and validity of the control.

從該組中移除一個控制元件。

Remove a control from this group.

      
      removeControl(name: string, options: { emitEvent?: boolean; } = {}): void
    
引數
name string

要從集合中移除的控制元件名

The control name to remove from the collection

options object

Specifies whether this FormGroup 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

This method also updates the value and validity of the control.

替換現有控制元件。

Replace an existing control.

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

要從集合中替換掉的控制元件名

The control name to replace in the collection

control AbstractControl

提供具有指定名稱的控制元件

Provides the control for the given name

options object

Specifies whether this FormGroup instance should emit events after an existing control is replaced.

  • 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

檢查組內是否有一個具有指定名字的已啟用的控制元件。

Check whether there is an enabled control with the given name in the group.

      
      contains(controlName: string): boolean
    
引數
controlName string

要在集合中檢查是否存在的控制元件名

The control name to check for existence in the collection

返回值

對於已禁用的控制元件返回 false,否則返回 true

boolean: false for disabled controls, true otherwise.

對於已禁用的控制元件,返回 false。如果你只想檢查它是否存在於該組中,請改用 get 代替。

Reports false for disabled controls. If you'd like to check for existence in the group only, use get instead.

設定此 FormGroup 的值。它接受一個與組結構對應的物件,以控制元件名作為 key。

Sets the value of the FormGroup. It accepts an object that matches the structure of the group, with control names as keys.

      
      setValue(value: { [key: string]: any; }, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void
    
引數
value object

控制元件的新值,其結構必須和該組的結構相匹配。

The new value for the control that matches the structure of the group.

options object

當值變化時,此配置項會決定該控制元件會如何傳播變更以及發出事件。該配置項會被傳給 updateValueAndValidity 方法。

Configuration options that determine how the control propagates changes and emits events after the value changes. The configuration options are passed to the updateValueAndValidity method.

  • onlySelf::如果為 true,則每個變更僅僅影響當前控制元件,而不會影響父控制元件。預設為 false

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

  • emitEvent:如果為 true 或未提供(預設),則當控制元件值發生變化時,statusChangesvalueChanges 這兩個 Observable 分別會以最近的狀態和值發出事件。 如果為 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.

可選. 預設值是 `{}`.
返回值

void

異常

錯誤 When strict checks fail, such as setting the value of a control that doesn't exist or if you exclude a value of a control that does exist.

當嚴格的檢查失敗時,比如設定了不存在的或被排除出去的控制元件的值。

使用說明

設定表單組的完整值
Set the complete value for the form group
      
      const form = new FormGroup({
  first: new FormControl(),
  last: new FormControl()
});

console.log(form.value);   // {first: null, last: null}

form.setValue({first: 'Nancy', last: 'Drew'});
console.log(form.value);   // {first: 'Nancy', last: 'Drew'}
    

修補此 FormGroup 的值。它接受一個以控制元件名為 key 的物件,並儘量把它們的值匹配到組中正確的控制元件上。

Patches the value of the FormGroup. It accepts an object with control names as keys, and does its best to match the values to the correct controls in the group.

      
      patchValue(value: { [key: string]: any; }, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void
    
引數
value object

與該組的結構匹配的物件。

The object that matches the structure of the group.

options object

在修補了該值之後,此配置項會決定控制元件如何傳播變更以及發出事件。

Configuration options that determine how the control propagates changes and emits events after the value is patched.

  • onlySelf:如果為 true,則每個變更僅僅影響當前控制元件,而不會影響父控制元件。預設為 false

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

  • 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 group without throwing an error.

使用說明

修補表單組的值
Patch the value for a form group
      
      const form = new FormGroup({
   first: new FormControl(),
   last: new FormControl()
});
console.log(form.value);   // {first: null, last: null}

form.patchValue({first: 'Nancy'});
console.log(form.value);   // {first: 'Nancy', last: null}
    

重置這個 FormGroup,把它的各級子控制元件都標記為 pristineuntouched,並把它們的值都設定為 null

Resets the FormGroup, marks all descendants pristine and untouched and sets the value of all descendants to null.

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

使用一個初始值或包含初始值與禁用狀態的物件重置該控制元件。

Resets the control with an initial value, or an object that defines the initial value and disabled state.

可選. 預設值是 `{}`.
options object

當該組被重置時,此配置項會決定該控制元件如何傳播變更以及發出事件。

Configuration options that determine how the control propagates changes and emits events when the group is reset.

  • 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

你可以透過傳入一個與表單結構相匹配的以控制元件名為 key 的 Map,來把表單重置為特定的狀態。 其狀態可以是一個單獨的值,也可以是一個同時具有值和禁用狀態的表單狀態物件。

You reset to a specific form state by passing in a map of states that matches the structure of your form, with control names as keys. The state is a standalone value or a form state object with both a value and a disabled status.

使用說明

重置該表單組的值
Reset the form group values
      
      const form = new FormGroup({
  first: new FormControl('first name'),
  last: new FormControl('last name')
});

console.log(form.value);  // {first: 'first name', last: 'last name'}

form.reset({ first: 'name', last: 'last name' });

console.log(form.value);  // {first: 'name', last: 'last name'}
    
重置該表單組的值以及禁用狀態
Reset the form group values and disabled status
      
      const form = new FormGroup({
  first: new FormControl('first name'),
  last: new FormControl('last name')
});

form.reset({
  first: {value: 'name', disabled: true},
  last: 'last'
});

console.log(form.value);  // {last: 'last'}
console.log(form.get('first').status);  // 'DISABLED'
    

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

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

      
      getRawValue(): any
    
引數

沒有引數。

返回值

any

獲取所有控制元件的值而不管其禁用狀態。 value 屬性是獲取組中的值的最佳方式,因為它從 FormGroup 中排除了所有已禁用的控制元件。

Retrieves all values regardless of disabled status. The value property is the best way to get the value of the group, because it excludes disabled controls in the FormGroup.

使用說明

建立一個帶有兩個控制元件的表單組

Create a form group with 2 controls

      
      const form = new FormGroup({
  first: new FormControl('Nancy', Validators.minLength(2)),
  last: new FormControl('Drew'),
});

console.log(form.value);   // {first: 'Nancy', last; 'Drew'}
console.log(form.status);  // 'VALID'
    

建立一個具有組級驗證器的表單組

Create a form group with a group-level validator

你可以用第二個引數傳入一些組級驗證器或用第三個引數傳入一些組級非同步驗證器。 當你要根據一個以上子控制元件的值來決定有效性時,這很好用。

You include group-level validators as the second arg, or group-level async validators as the third arg. These come in handy when you want to perform validation that considers the value of more than one child control.

      
      const form = new FormGroup({
  password: new FormControl('', Validators.minLength(2)),
  passwordConfirm: new FormControl('', Validators.minLength(2)),
}, passwordMatchValidator);


function passwordMatchValidator(g: FormGroup) {
   return g.get('password').value === g.get('passwordConfirm').value
      ? null : {'mismatch': true};
}
    

FormControl 實例一樣,你也可以在配置物件中傳入驗證器和非同步驗證器。

Like FormControl instances, you choose to pass in validators and async validators as part of an options object.

      
      const form = new FormGroup({
  password: new FormControl('')
  passwordConfirm: new FormControl('')
}, { validators: passwordMatchValidator, asyncValidators: otherValidator });
    

為表單組中的所有空間設定 updateOn 屬性

Set the updateOn property for all controls in a form group

該選項物件可用來為每個子控制元件的 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 group level, all child controls default to 'blur', unless the child has explicitly specified a different updateOn value.

      
      const c = new FormGroup({
  one: new FormControl()
}, { updateOn: 'blur' });