FormGroup

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

跟踪一组 FormControl 实例的值和有效性状态。

class FormGroup extends AbstractControl { constructor(controls: {...}, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null) 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: {...}, options: {...}): void patchValue(value: {...}, 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 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 把每个子 FormControl 的值聚合进一个对象,它的 key 是每个控件的名字。 它通过归集其子控件的状态值来计算出自己的状态。 比如,如果组中的任何一个控件是无效的,那么整个组就是无效的。

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

FormGroup 是 Angular 中用来定义表单的三大基本构造块之一,就像 FormControlFormArray 一样。

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.

创建一个新的 FormGroup 实例

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

参数

controls

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

一组子控件。每个子控件的名字就是它注册时用的 key

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

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

一组子控件。每个子控件的名字就是它注册时用的 key

声明于构造函数中

方法

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

向组内的控件列表中注册一个控件。

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

参数

name

The control name to register in the collection

注册到集合中的控件名

control

Provides the control for the given name

提供这个名字对应的控件

返回值

AbstractControl

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

该方法不会更新控件的值或其有效性。 使用 addControl 代替。

Add a control to this group.

往组中添加一个控件。

addControl(name: string, control: AbstractControl): void

参数

name

The control name to add to the collection

要注册到集合中的控件名

control

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

参数

name

The control name to remove from the collection

要从集合中移除的控件名

返回值

void

Replace an existing control.

替换现有控件。

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

参数

name

The control name to replace in the collection

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

control

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

参数

controlName

Type: string.

返回值

boolean: false for disabled controls, true otherwise.

对于已禁用的控件返回 false,否则返回 true

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

对于已禁用的控件,返回 false。如果你只想检查它是否存在于该组中,请改用 get 代替。

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

设置此 FormGroup 的值。它接受一个与组结构对应的对象,以控件名作为 key。

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

参数

value

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

控件的新值,其结构必须和该组的结构相匹配。

options

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.

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

  • 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.

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

可选. 默认值是 {}.

返回值

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

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.

修补此 FormGroup 的值。它接受一个以控件名为 key 的对象,并尽量把它们的值匹配到组中正确的控件上。

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

参数

value

The object that matches the structure of the group

与该组的结构匹配的对象

options

Configure options that determines how the control propagates changes and emits events after the value is patched

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

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

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

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

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

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

参数

value

Type: any.

可选. 默认值是 {}.

options

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

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

  • 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 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.

你可以通过传入一个与表单结构相匹配的以控件名为 key 的 Map,来把表单重置为特定的状态。 其状态可以是一个单独的值,也可以是一个同时具有值和禁用状态的表单状态对象。

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(this.form.value); // {first: 'name', last: 'last name'} console.log(this.form.get('first').status); // 'DISABLED'

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

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

getRawValue(): any

参数

没有参数。

返回值

any

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.

获取所有控件的值而不管其禁用状态。 value 属性是获取组中的值的最佳方式,因为它从 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}; }

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

FormControl 实例一样,你也可以在配置对象中传入验证器和异步验证器。

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

Set the updateOn property for all controls in a form group

为表单组中的所有空间设置 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.

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

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