FormControl

class

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

See more...

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

  // inherited from forms/AbstractControl
  constructor(validator: ValidatorFn | null, asyncValidator: AsyncValidatorFn | null)
  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[] | 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
}

See also

Description

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.

Constructor

Creates a new FormControl instance.

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

Parameters

formState

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

Optional. Default is null.

validatorOrOpts

A synchronous validator function, or an array of such functions, or an AbstractControlOptions object that contains validation functions and a validation trigger.

Optional. Default is undefined.

asyncValidator

A single async validator or array of async validator functions

Optional. Default is undefined.

Methods

Sets a new value for the form control.

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

Parameters

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.

  • onlySelf: When true, each change only affects this control, and not its parent. Default is 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: When true or not supplied (the default), each change triggers an onChange event to update the view.
  • emitViewToModelChange: When true or not supplied (the default), each change triggers an ngModelChange event to update the model.

Optional. Default is {}.

Returns

void

Patches the value of a control.

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

Parameters

value

Type: any.

options

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

Optional. Default is {}.

Returns

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.

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

Parameters

formState

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

Optional. Default is 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.
  • 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.

Optional. Default is {}.

Returns

void

Register a listener for change events.

registerOnChange(fn: Function): void

Parameters

fn

The method that is called when the value changes

Returns

void

Register a listener for disabled events.

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

Parameters

fn

The method that is called when the disabled status changes.

Returns

void

Usage notes

Initializing Form Controls

Instantiate a FormControl, with an initial value.

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

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

Configure the control to update on a blur event

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

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

Configure the control to update on a submit event

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'

© 2010–2019 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://v6.angular.io/api/forms/FormControl