填写这份《一分钟调查》,帮我们(开发组)做得更好!去填写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): void removeControl(name: string): void setControl(name: string, control: AbstractControl): 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(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 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 }
      
      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): void
  removeControl(name: string): void
  setControl(name: string, control: AbstractControl): 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(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
  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.

构造函数

创建一个新的 FormGroup 实例

Creates a new FormGroup instance.

constructor(controls: { [key: string]: AbstractControl; }, validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[])
      
      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; } Declared in constructor.

一组子控件。每个子控件的名字就是它注册时用的 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
      
      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): void
      
      addControl(name: string, control: AbstractControl): void
    
参数
name string

要注册到集合中的控件名

The control name to add to the collection

control AbstractControl

提供与该控件名对应的控件。

Provides the control for the given name

返回值

void

该方法还会更新本空间的值和有效性。

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

从该组中移除一个控件。

Remove a control from this group.

removeControl(name: string): void
      
      removeControl(name: string): void
    
参数
name string

要从集合中移除的控件名

The control name to remove from the collection

返回值

void

替换现有控件。

Replace an existing control.

setControl(name: string, control: AbstractControl): void
      
      setControl(name: string, control: AbstractControl): void
    
参数
name string

要从集合中替换掉的控件名

The control name to replace in the collection

control AbstractControl

提供具有指定名称的控件

Provides the control for the given name

返回值

void

检查组内是否有一个具有指定名字的已启用的控件。

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

contains(controlName: string): boolean
      
      contains(controlName: string): boolean
    
参数
controlName string
返回值

对于已禁用的控件返回 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
      
      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 excluding the value of a control.

当严格的检查失败时,比如设置了不存在的或被排除出去的控件的值。

使用说明

设置表单组的完整值
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'}
      
      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
      
      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}
      
      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 are marked pristine and untouched, and the value of all descendants to null.

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

可选. 默认值是 {}.

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'}
      
      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(this.form.value); // {first: 'name', last: 'last name'} console.log(this.form.get('first').status); // 'DISABLED'
      
      
  1. const form = new FormGroup({
  2. first: new FormControl('first name'),
  3. last: new FormControl('last name')
  4. });
  5.  
  6. form.reset({
  7. first: {value: 'name', disabled: true},
  8. last: 'last'
  9. });
  10.  
  11. console.log(this.form.value); // {first: 'name', last: 'last name'}
  12. console.log(this.form.get('first').status); // 'DISABLED'

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

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

getRawValue(): any
      
      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'
      
      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}; }
      
      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 });
      
      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' });
      
      const c = new FormGroup({
  one: new FormControl()
}, { updateOn: 'blur' });