W3cubDocs

/Angular

FormControl

class final

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

See more...

class FormControl<TValue = any> extends AbstractControl<TValue> {
  new (): FormControl<any>
  defaultValue: TValue
  setValue(value: TValue, options?: { onlySelf?: boolean; emitEvent?: boolean; emitModelToViewChange?: boolean; emitViewToModelChange?: boolean; }): void
  patchValue(value: TValue, options?: { onlySelf?: boolean; emitEvent?: boolean; emitModelToViewChange?: boolean; emitViewToModelChange?: boolean; }): void
  reset(formState?: TValue | FormControlState<TValue>, options?: { onlySelf?: boolean; emitEvent?: boolean; }): void
  getRawValue(): TValue
  registerOnChange(fn: Function): void
  registerOnDisabledChange(fn: (isDisabled: boolean) => void): void

  // inherited from forms/AbstractControl
  constructor(validators: ValidatorFn | ValidatorFn[], asyncValidators: AsyncValidatorFn | AsyncValidatorFn[])
  value: TValue
  validator: ValidatorFn | null
  asyncValidator: AsyncValidatorFn | null
  parent: FormGroup | FormArray | null
  status: FormControlStatus
  valid: boolean
  invalid: boolean
  pending: boolean
  disabled: boolean
  enabled: boolean
  errors: ValidationErrors | null
  pristine: boolean
  dirty: boolean
  touched: boolean
  untouched: boolean
  valueChanges: Observable<TValue>
  statusChanges: Observable<FormControlStatus>
  updateOn: FormHooks
  root: AbstractControl
  setValidators(validators: ValidatorFn | ValidatorFn[]): void
  setAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void
  addValidators(validators: ValidatorFn | ValidatorFn[]): void
  addAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void
  removeValidators(validators: ValidatorFn | ValidatorFn[]): void
  removeAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void
  hasValidator(validator: ValidatorFn): boolean
  hasAsyncValidator(validator: AsyncValidatorFn): boolean
  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<any> | FormArray<any>): void
  abstract setValue(value: TRawValue, options?: Object): void
  abstract patchValue(value: TValue, options?: Object): void
  abstract reset(value?: TValue, options?: Object): void
  getRawValue(): any
  updateValueAndValidity(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void
  setErrors(errors: ValidationErrors, opts: { emitEvent?: boolean; } = {}): void
  get<P extends string | ((string | number)[])>(path: P): AbstractControl<ɵGetProperty<TRawValue, P>> | null
  getError(errorCode: string, path?: string | (string | number)[]): any
  hasError(errorCode: string, path?: string | (string | number)[]): boolean
}

See also

Description

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

FormControl takes a single generic argument, which describes the type of its value. This argument always implicitly includes null because the control can be reset. To change this behavior, set nonNullable or see the usage notes below.

See usage examples below.

Further information is available in the Usage Notes...

Constructor

Construct a FormControl with no initial value or validators.

4 overloads...

Show All Hide All
Overload #1

Creates a new FormControl instance.

new <T = any>(value: T | FormControlState<T>, opts: FormControlOptions & { nonNullable: true; }): FormControl<T>

Parameters
value T | FormControlState<T>
opts FormControlOptions & { nonNullable: true; }
Returns

FormControl<T>

Overload #2

new <T = any>(value: T | FormControlState<T>, opts: FormControlOptions & { initialValueIsDefault: true; }): FormControl<T>

Deprecated Use nonNullable instead.

Parameters
value T | FormControlState<T>
opts FormControlOptions & { initialValueIsDefault: true; }
Returns

FormControl<T>

Overload #3

new <T = any>(value: T | FormControlState<T>, opts: FormControlOptions, asyncValidator: AsyncValidatorFn | AsyncValidatorFn[]): FormControl<T | null>

Deprecated When passing an options argument, the asyncValidator argument has no effect.

Parameters
value T | FormControlState<T>
opts FormControlOptions
asyncValidator AsyncValidatorFn | AsyncValidatorFn[]
Returns

FormControl<T | null>

Overload #4

new <T = any>(value: T | FormControlState<T>, validatorOrOpts?: ValidatorFn | FormControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]): FormControl<T | null>

Parameters
value T | FormControlState<T>
validatorOrOpts ValidatorFn | FormControlOptions | ValidatorFn[]

Optional. Default is undefined.

asyncValidator AsyncValidatorFn | AsyncValidatorFn[]

Optional. Default is undefined.

Returns

FormControl<T | null>

Properties

Property Description
defaultValue: TValue Read-Only

The default value of this FormControl, used whenever the control is reset without an explicit value. See FormControlOptions#nonNullable for more information on configuring a default value.

Methods

Sets a new value for the form control.

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

Parameters
value TValue

The new value for the control.

options object

Configuration options that determine how the control propagates changes and emits events when the value changes. The configuration options are passed to the AbstractControl#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 undefined.

Returns

void

Patches the value of a control.

See also:

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

Parameters
value TValue
options object

Optional. Default is undefined.

Returns

void

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

Resets the form control, marking it pristine and untouched, and resetting the value. The new value will be the provided value (if passed), null, or the initial value if nonNullable was set in the constructor via FormControlOptions.

reset(formState?: TValue | FormControlState<TValue>, options?: { onlySelf?: boolean; emitEvent?: boolean; }): void

Parameters
formState TValue | FormControlState<TValue>

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

Optional. Default is undefined.

options object

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

Returns

void

// By default, the control will reset to null.
const dog = new FormControl('spot');
dog.reset(); // dog.value is null

// If this flag is set, the control will instead reset to the initial value.
const cat = new FormControl('tabby', {nonNullable: true});
cat.reset(); // cat.value is "tabby"

// A value passed to reset always takes precedence.
const fish = new FormControl('finn', {nonNullable: true});
fish.reset('bubble'); // fish.value is "bubble"

For a simple FormControl, the raw value is equivalent to the value.

getRawValue(): TValue

Parameters

There are no parameters.

Returns

TValue

Register a listener for change events.

registerOnChange(fn: Function): void

Parameters
fn Function

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 (isDisabled: boolean) => void

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

The single type argument

FormControl accepts a generic argument, which describes the type of its value. In most cases, this argument will be inferred.

If you are initializing the control to null, or you otherwise wish to provide a wider type, you may specify the argument explicitly:

let fc = new FormControl<string|null>(null);
fc.setValue('foo');

You might notice that null is always added to the type of the control. This is because the control will become null if you call reset. You can change this behavior by setting {nonNullable: true}.

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 a specific 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 to its initial value

If you wish to always reset the control to its initial value (instead of null), you can pass the nonNullable option:

const control = new FormControl('Nancy', {nonNullable: true});

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

control.reset();

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

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–2023 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/api/forms/FormControl