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

FormControl

追蹤獨立表單控制元件的值和驗證狀態。

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

檢視"說明"...

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

參見

說明

它和 FormGroupFormArray 是 Angular 表單的三大基本構成要素之一。 它擴充套件了 AbstractControl 類別,並實現了關於訪問值、驗證狀態、使用者互動和事件的大部分基本功能。

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. See usage examples below.

Further information available in the Usage Notes...

建構函式

建立新的 FormControl 實例。

Creates a new FormControl instance.

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

使用一個初始值或定義了初始值和禁用狀態的物件初始化該控制元件。

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

可選. 預設值是 `null`.
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`.

方法

設定該表單控制元件的新值。

Sets a new value for the form control.

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

控制元件的新值。

The new value for the control.

options object

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

Configuration options that determine how the control propagates changes and emits events when 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.

  • emitModelToViewChange:如果為 true 或未提供(預設),則每次變化都會觸發一個 onChange 事件以更新檢視。

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

  • emitViewToModelChange:如果為 true 或未提供(預設),則每次變化都會觸發一個 ngModelChange 事件以更新模型。

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

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

void

修補控制元件的值。

Patches the value of a control.

See also:

  • setValue 的配置項

    setValue for options

      
      patchValue(value: any, options: { onlySelf?: boolean; emitEvent?: boolean; emitModelToViewChange?: boolean; emitViewToModelChange?: boolean; } = {}): void
    
引數
value any
options object
可選. 預設值是 `{}`.
返回值

void

FormControl 這個層次上,該函式的功能和 setValue 完全相同。 但 FormGroupFormArray 上的 patchValue 則具有不同的行為。

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.

重置該表單控制元件,把它標記為 pristineuntouched,並把它的值設定為 null

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

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

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

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

可選. 預設值是 `null`.
options object

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

Configuration 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,則不會發出事件。

    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.

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

void

註冊變更事件的監聽器。

Register a listener for change events.

      
      registerOnChange(fn: Function): void
    
引數
fn Function

當值變化時,就會呼叫該方法。

The method that is called when the value changes

返回值

void

註冊禁用事件的監聽器。

Register a listener for disabled events.

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

當禁用狀態發生變化時,就會呼叫該方法。

The method that is called when the disabled status changes.

返回值

void

使用說明

初始化表單控制元件

Initializing Form Controls

用一個初始值初始化 FormControl

Instantiate a FormControl, with an initial value.

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

下面的例子用一個表單狀態物件初始化控制元件。這裡用到的是 valuedisabled 鍵。

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

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

下面的例子使用一個同步驗證器初始化了該控制元件。

The following example initializes the control with a sync validator.

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

下面的例子使用一個配置物件初始化了該控制元件。

The following example initializes the control using an options object.

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

配置該控制元件,使其在發生 blur 事件時更新

Configure the control to update on a blur event

updateOn 選項設定為 'blur',可以在發生 blur 事件時更新。

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

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

配置該控制元件,使其在發生 submit 事件時更新

Configure the control to update on a submit event

updateOn 選項設定為 'submit',可以在發生 submit 事件時更新。

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

      
      const control = 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 control = 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 control = new FormControl('Nancy');

console.log(control.value); // 'Nancy'
console.log(control.status); // 'VALID'

control.reset({ value: 'Drew', disabled: true });

console.log(control.value); // 'Drew'
console.log(control.status); // 'DISABLED'