W3cubDocs

/Angular 12

AbstractControl

class

This is the base class for FormControl, FormGroup, and FormArray.

See more...

abstract class 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(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 | 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
}

See also

Description

It provides some of the shared behavior that all controls and groups of controls have, like running validators, calculating status, and resetting state. It also defines the properties that are shared between all sub-classes, like value, valid, and dirty. It shouldn't be instantiated directly.

Constructor

Initialize the AbstractControl instance.

constructor(validators: ValidatorFn | ValidatorFn[], asyncValidators: AsyncValidatorFn | AsyncValidatorFn[])

Parameters
validators ValidatorFn | ValidatorFn[]

The function or array of functions that is used to determine the validity of this control synchronously.

asyncValidators AsyncValidatorFn | AsyncValidatorFn[]

The function or array of functions that is used to determine validity of this control asynchronously.

Properties

Property Description
value: any Read-Only

The current value of the control.

  • For a FormControl, the current value.
  • For an enabled FormGroup, the values of enabled controls as an object with a key-value pair for each member of the group.
  • For a disabled FormGroup, the values of all controls as an object with a key-value pair for each member of the group.
  • For a FormArray, the values of enabled controls as an array.
validator: ValidatorFn | null

Returns the function that is used to determine the validity of this control synchronously. If multiple validators have been added, this will be a single composed function. See Validators.compose() for additional information.

asyncValidator: AsyncValidatorFn | null

Returns the function that is used to determine the validity of this control asynchronously. If multiple validators have been added, this will be a single composed function. See Validators.compose() for additional information.

parent: FormGroup | FormArray | null Read-Only

The parent control.

status: string Read-Only

The validation status of the control. There are four possible validation status values:

  • VALID: This control has passed all validation checks.
  • INVALID: This control has failed at least one validation check.
  • PENDING: This control is in the midst of conducting a validation check.
  • DISABLED: This control is exempt from validation checks.

These status values are mutually exclusive, so a control cannot be both valid AND invalid or invalid AND disabled.

valid: boolean Read-Only

A control is valid when its status is VALID.

See also:

invalid: boolean Read-Only

A control is invalid when its status is INVALID.

See also:

pending: boolean Read-Only

A control is pending when its status is PENDING.

See also:

disabled: boolean Read-Only

A control is disabled when its status is DISABLED.

Disabled controls are exempt from validation checks and are not included in the aggregate value of their ancestor controls.

See also:

enabled: boolean Read-Only

A control is enabled as long as its status is not DISABLED.

See also:

errors: ValidationErrors | null Read-Only

An object containing any errors generated by failing validation, or null if there are no errors.

pristine: boolean Read-Only

A control is pristine if the user has not yet changed the value in the UI.

dirty: boolean Read-Only

A control is dirty if the user has changed the value in the UI.

touched: boolean Read-Only

True if the control is marked as touched.

A control is marked touched once the user has triggered a blur event on it.

untouched: boolean Read-Only

True if the control has not been marked as touched

A control is untouched if the user has not yet triggered a blur event on it.

valueChanges: Observable<any> Read-Only

A multicasting observable that emits an event every time the value of the control changes, in the UI or programmatically. It also emits an event each time you call enable() or disable() without passing along {emitEvent: false} as a function argument.

statusChanges: Observable<any> Read-Only

A multicasting observable that emits an event every time the validation status of the control recalculates.

See also:

updateOn: FormHooks Read-Only

Reports the update strategy of the AbstractControl (meaning the event on which the control updates itself). Possible values: 'change' | 'blur' | 'submit' Default value: 'change'

root: AbstractControl Read-Only

Retrieves the top-level ancestor of this control.

Methods

Sets the synchronous validators that are active on this control. Calling this overwrites any existing synchronous validators.

setValidators(validators: ValidatorFn | ValidatorFn[]): void

Parameters
validators ValidatorFn | ValidatorFn[]
Returns

void

When you add or remove a validator at run time, you must call updateValueAndValidity() for the new validation to take effect.

If you want to add a new validator without affecting existing ones, consider using addValidators() method instead.

Sets the asynchronous validators that are active on this control. Calling this overwrites any existing asynchronous validators.

setAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void

Parameters
validators AsyncValidatorFn | AsyncValidatorFn[]
Returns

void

When you add or remove a validator at run time, you must call updateValueAndValidity() for the new validation to take effect.

If you want to add a new validator without affecting existing ones, consider using addAsyncValidators() method instead.

Add a synchronous validator or validators to this control, without affecting other validators.

addValidators(validators: ValidatorFn | ValidatorFn[]): void

Parameters
validators ValidatorFn | ValidatorFn[]

The new validator function or functions to add to this control.

Returns

void

When you add or remove a validator at run time, you must call updateValueAndValidity() for the new validation to take effect.

Adding a validator that already exists will have no effect. If duplicate validator functions are present in the validators array, only the first instance would be added to a form control.

Add an asynchronous validator or validators to this control, without affecting other validators.

addAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void

Parameters
validators AsyncValidatorFn | AsyncValidatorFn[]

The new asynchronous validator function or functions to add to this control.

Returns

void

When you add or remove a validator at run time, you must call updateValueAndValidity() for the new validation to take effect.

Adding a validator that already exists will have no effect.

Remove a synchronous validator from this control, without affecting other validators. Validators are compared by function reference; you must pass a reference to the exact same validator function as the one that was originally set. If a provided validator is not found, it is ignored.

removeValidators(validators: ValidatorFn | ValidatorFn[]): void

Parameters
validators ValidatorFn | ValidatorFn[]

The validator or validators to remove.

Returns

void

When you add or remove a validator at run time, you must call updateValueAndValidity() for the new validation to take effect.

Remove an asynchronous validator from this control, without affecting other validators. Validators are compared by function reference; you must pass a reference to the exact same validator function as the one that was originally set. If a provided validator is not found, it is ignored.

removeAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void

Parameters
validators AsyncValidatorFn | AsyncValidatorFn[]

The asynchronous validator or validators to remove.

Returns

void

When you add or remove a validator at run time, you must call updateValueAndValidity() for the new validation to take effect.

Check whether a synchronous validator function is present on this control. The provided validator must be a reference to the exact same function that was provided.

hasValidator(validator: ValidatorFn): boolean

Parameters
validator ValidatorFn

The validator to check for presence. Compared by function reference.

Returns

boolean: Whether the provided validator was found on this control.

Check whether an asynchronous validator function is present on this control. The provided validator must be a reference to the exact same function that was provided.

hasAsyncValidator(validator: AsyncValidatorFn): boolean

Parameters
validator AsyncValidatorFn

The asynchronous validator to check for presence. Compared by function reference.

Returns

boolean: Whether the provided asynchronous validator was found on this control.

Empties out the synchronous validator list.

clearValidators(): void

Parameters

There are no parameters.

Returns

void

When you add or remove a validator at run time, you must call updateValueAndValidity() for the new validation to take effect.

Empties out the async validator list.

clearAsyncValidators(): void

Parameters

There are no parameters.

Returns

void

When you add or remove a validator at run time, you must call updateValueAndValidity() for the new validation to take effect.

Marks the control as touched. A control is touched by focus and blur events that do not change the value.

See also:

  • markAsUntouched()

  • markAsDirty()

  • markAsPristine()

markAsTouched(opts: { onlySelf?: boolean; } = {}): void

Parameters
opts object

Configuration options that determine how the control propagates changes and emits events after marking is applied.

  • onlySelf: When true, mark only this control. When false or not supplied, marks all direct ancestors. Default is false.

Optional. Default is {}.

Returns

void

Marks the control and all its descendant controls as touched.

See also:

  • markAsTouched()

markAllAsTouched(): void

Parameters

There are no parameters.

Returns

void

Marks the control as untouched.

See also:

  • markAsTouched()

  • markAsDirty()

  • markAsPristine()

markAsUntouched(opts: { onlySelf?: boolean; } = {}): void

Parameters
opts object

Configuration options that determine how the control propagates changes and emits events after the marking is applied.

  • onlySelf: When true, mark only this control. When false or not supplied, marks all direct ancestors. Default is false.

Optional. Default is {}.

Returns

void

If the control has any children, also marks all children as untouched and recalculates the touched status of all parent controls.

Marks the control as dirty. A control becomes dirty when the control's value is changed through the UI; compare markAsTouched.

See also:

  • markAsTouched()

  • markAsUntouched()

  • markAsPristine()

markAsDirty(opts: { onlySelf?: boolean; } = {}): void

Parameters
opts object

Configuration options that determine how the control propagates changes and emits events after marking is applied.

  • onlySelf: When true, mark only this control. When false or not supplied, marks all direct ancestors. Default is false.

Optional. Default is {}.

Returns

void

Marks the control as pristine.

See also:

  • markAsTouched()

  • markAsUntouched()

  • markAsDirty()

markAsPristine(opts: { onlySelf?: boolean; } = {}): void

Parameters
opts object

Configuration options that determine how the control emits events after marking is applied.

  • onlySelf: When true, mark only this control. When false or not supplied, marks all direct ancestors. Default is false.

Optional. Default is {}.

Returns

void

If the control has any children, marks all children as pristine, and recalculates the pristine status of all parent controls.

Marks the control as pending.

See also:

markAsPending(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void

Parameters
opts object

Configuration options that determine how the control propagates changes and emits events after marking is applied.

  • onlySelf: When true, mark only this control. When false or not supplied, marks all direct ancestors. Default is false.
  • emitEvent: When true or not supplied (the default), the statusChanges observable emits an event with the latest status the control is marked pending. When false, no events are emitted.

Optional. Default is {}.

Returns

void

A control is pending while the control performs async validation.

Disables the control. This means the control is exempt from validation checks and excluded from the aggregate value of any parent. Its status is DISABLED.

See also:

disable(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void

Parameters
opts object

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

  • onlySelf: When true, mark only this control. When false or not supplied, marks all direct ancestors. 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 disabled. When false, no events are emitted.

Optional. Default is {}.

Returns

void

If the control has children, all children are also disabled.

Enables the control. This means the control is included in validation checks and the aggregate value of its parent. Its status recalculates based on its value and its validators.

See also:

enable(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void

Parameters
opts object

Configure options that control how the control propagates changes and emits events when marked as untouched

  • onlySelf: When true, mark only this control. When false or not supplied, marks all direct ancestors. 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 enabled. When false, no events are emitted.

Optional. Default is {}.

Returns

void

By default, if the control has children, all children are enabled.

setParent(parent: FormGroup | FormArray): void

Parameters
parent FormGroup | FormArray

Sets the parent of the control

Returns

void

Sets the value of the control. Abstract method (implemented in sub-classes).

abstract setValue(value: any, options?: Object): void

Parameters
value any
options Object

Optional. Default is undefined.

Returns

void

Patches the value of the control. Abstract method (implemented in sub-classes).

abstract patchValue(value: any, options?: Object): void

Parameters
value any
options Object

Optional. Default is undefined.

Returns

void

Resets the control. Abstract method (implemented in sub-classes).

abstract reset(value?: any, options?: Object): void

Parameters
value any

Optional. Default is undefined.

options Object

Optional. Default is undefined.

Returns

void

Recalculates the value and validation status of the control.

updateValueAndValidity(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void

Parameters
opts object

Configuration options determine how the control propagates changes and emits events after updates and validity checks are applied.

  • onlySelf: When true, only update this control. When false or not supplied, update all direct ancestors. 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 updated. When false, no events are emitted.

Optional. Default is {}.

Returns

void

By default, it also updates the value and validity of its ancestors.

Sets errors on a form control when running validations manually, rather than automatically.

setErrors(errors: ValidationErrors, opts: { emitEvent?: boolean; } = {}): void

Parameters
errors ValidationErrors
opts object

Optional. Default is {}.

Returns

void

Calling setErrors also updates the validity of the parent control.

Usage Notes

Manually set the errors for a control
const login = new FormControl('someLogin');
login.setErrors({
  notUnique: true
});

expect(login.valid).toEqual(false);
expect(login.errors).toEqual({ notUnique: true });

login.setValue('someOtherLogin');

expect(login.valid).toEqual(true);

Retrieves a child control given the control's name or path.

get(path: string | (string | number)[]): AbstractControl | null

Parameters
path string | (string | number)[]

A dot-delimited string or array of string/number values that define the path to the control.

Returns

AbstractControl | null

Usage Notes

Retrieve a nested control

For example, to get a name control nested within a person sub-group:

  • this.form.get('person.name');

-OR-

  • this.form.get(['person', 'name']);
Retrieve a control in a FormArray

When accessing an element inside a FormArray, you can use an element index. For example, to get a price control from the first element in an items array you can use:

  • this.form.get('items.0.price');

-OR-

  • this.form.get(['items', 0, 'price']);

Reports error data for the control with the given path.

getError(errorCode: string, path?: string | (string | number)[]): any

Parameters
errorCode string

The code of the error to check

path string | (string | number)[]

A list of control names that designates how to move from the current control to the control that should be queried for errors.

Optional. Default is undefined.

Returns

any: error data for that particular error. If the control or error is not present, null is returned.

Usage Notes

For example, for the following FormGroup:

form = new FormGroup({
  address: new FormGroup({ street: new FormControl() })
});

The path to the 'street' control from the root form would be 'address' -> 'street'.

It can be provided to this method in one of two formats:

  1. An array of string control names, e.g. ['address', 'street']
  2. A period-delimited list of control names in one string, e.g. 'address.street'

Reports whether the control with the given path has the error specified.

hasError(errorCode: string, path?: string | (string | number)[]): boolean

Parameters
errorCode string

The code of the error to check

path string | (string | number)[]

A list of control names that designates how to move from the current control to the control that should be queried for errors.

Optional. Default is undefined.

Returns

boolean: whether the given error is present in the control at the given path.

If the control is not present, false is returned.

Usage Notes

For example, for the following FormGroup:

form = new FormGroup({
  address: new FormGroup({ street: new FormControl() })
});

The path to the 'street' control from the root form would be 'address' -> 'street'.

It can be provided to this method in one of two formats:

  1. An array of string control names, e.g. ['address', 'street']
  2. A period-delimited list of control names in one string, e.g. 'address.street'

If no path is given, this method checks for the error on the current control.

© 2010–2021 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://v12.angular.io/api/forms/AbstractControl