FormControl

Tracks the value and validation status of an individual form control.

跟踪独立表单控件的值和验证状态。

class FormControl extends AbstractControl { constructor(formState: any = null, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null) setValue(value: any, options: {...}): void patchValue(value: any, options: {...}): void reset(formState: any = null, options: {...}): void registerOnChange(fn: Function): void registerOnDisabledChange(fn: (isDisabled: boolean) => void): void // 继承自 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 }

参见

说明

This is one of the three fundamental building blocks of Angular forms, along with FormGroup and FormArray. It extends the AbstractControl class that implements most of the base functionality for accessing the value, validation status, user interactions and events.

它和 FormGroupFormArray 是 Angular 表单的三大基本构造块之一。 它扩展了 AbstractControl 类,并实现了关于访问值、验证状态、用户交互和事件的大部分基本功能。

构造函数

Creates a new FormControl instance.

创建新的 FormControl 实例。

constructor(formState: any = null, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null)

参数

formState

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

使用一个初始值或定义了初始值和禁用状态的对象初始化该控件。

可选. 默认值是 null.

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.

方法

Sets a new value for the form control.

设置该表单控件的新值。

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

参数

value

The new value for the control.

控件的新值。

options

Configuration options that determine how the control proopagates changes and emits events when 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,则不会发出事件。

  • emitModelToViewChange: When true or not supplied (the default), each change triggers an onChange event to update the view.

    emitModelToViewChange:如果为 true 或未提供(默认),则每次变化都会触发一个 onChange 事件以更新视图。

  • emitViewToModelChange: When true or not supplied (the default), each change triggers an ngModelChange event to update the model.

    emitViewToModelChange:如果为 true 或未提供(默认),则每次变化都会触发一个 ngModelChange 事件以更新模型。

可选. 默认值是 {}.

返回值

void

Patches the value of a control.

修补控件的值。

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

参数

value

Type: any.

options

Type: { onlySelf?: boolean; emitEvent?: boolean; emitModelToViewChange?: boolean; emitViewToModelChange?: boolean; }.

可选. 默认值是 {}.

返回值

void

This function is functionally the same as setValue at this level. It exists for symmetry with patchValue on FormGroups and FormArrays, where it does behave differently.

FormControl 这个层次上,该函数的功能和 setValue 完全相同。 但 FormGroupFormArray 上的 patchValue 则具有不同的行为。

Resets the form control, marking it pristine and untouched, and setting the value to null.

重置该表单控件,把它标记为 pristineuntouched,并把它的值设置为 null

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

参数

formState

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

使用初始值或一个包含初始值和禁用状态的对象来重置该控件。

可选. 默认值是 null.

options

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

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

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

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

可选. 默认值是 {}.

返回值

void

Register a listener for change events.

注册变更事件的监听器。

registerOnChange(fn: Function): void

参数

fn

The method that is called when the value changes

当值变化时,就会调用该方法。

返回值

void

Register a listener for disabled events.

注册禁用事件的监听器。

registerOnDisabledChange(fn: (isDisabled: boolean) => void): void

参数

fn

The method that is called when the disabled status changes.

当禁用状态发生变化时,就会调用该方法。

返回值

void

使用说明

Initializing Form Controls

初始化表单控件

Instantiate a FormControl, with an initial value.

用一个初始值初始化 FormControl

const ctrl = new FormControl('some value'); console.log(ctrl.value); // 'some value'

The following example initializes the control with a form state object. The value and disabled keys are required in this case.

下面的例子用一个表单状态对象初始化控件。这里用到的是 valuedisabled 键。

const ctrl = new FormControl({ value: 'n/a', disabled: true }); console.log(ctrl.value); // 'n/a' console.log(ctrl.status); // 'DISABLED'

The following example initializes the control with a sync validator.

下面的例子使用一个同步验证器初始化了该控件。

const ctrl = new FormControl('', Validators.required); console.log(ctrl.value); // '' console.log(ctrl.status); // 'INVALID'

The following example initializes the control using an options object.

下面的例子使用一个配置对象初始化了该控件。

const ctrl = new FormControl('', { validators: Validators.required, asyncValidators: myAsyncValidator });

Configure the control to update on a blur event

配置该控件,使其在发生 blur 事件时更新

Set the updateOn option to 'blur' to update on the blur event.

updateOn 选项设置为 'blur',可以在发生 blur 事件时更新。

const ctrl = new FormControl('', { updateOn: 'blur' });

Configure the control to update on a submit event

配置该控件,使其在发生 submit 事件时更新

Set the updateOn option to 'submit' to update on a submit event.

updateOn 选项设置为 'submit',可以在发生 submit 事件时更新。

const ctrl = new FormControl('', { updateOn: 'submit' });

Reset the control back to an initial value

把该控件重置回初始值

You reset to a specific form state by passing through a standalone value or a form state object that contains both a value and a disabled state (these are the only two properties that cannot be calculated).

通过传递包含值和禁用状态的独立值或表单状态对象,可以将其重置为特定的表单状态(这是所支持的仅有的两个非计算状态)。

const ctrl = new FormControl('Nancy'); console.log(control.value); // 'Nancy' control.reset('Drew'); console.log(control.value); // 'Drew'

Reset the control back to an initial value and disabled

把该控件重置回初始值并禁用。

const ctrl = new FormControl('Nancy'); console.log(control.value); // 'Nancy' console.log(this.control.status); // 'DISABLED' control.reset({ value: 'Drew', disabled: true }); console.log(this.control.value); // 'Drew' console.log(this.control.status); // 'DISABLED'