FormControl
Tracks the value and validation status of an individual form control.
defaultValue
TValueThe 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.
setValue
voidSets a new value for the form control.
TValueThe new value for the control.
{ onlySelf?: boolean | undefined; emitEvent?: boolean | undefined; emitModelToViewChange?: boolean | undefined; emitViewToModelChange?: boolean | undefined; } | undefinedConfiguration 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: When true, each change only affects this control, and not its parent. Default is false.emitEvent: When true or not supplied (the default), both thestatusChangesandvalueChangesobservables 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 anonChangeevent to update the view.emitViewToModelChange: When true or not supplied (the default), each change triggers anngModelChangeevent to update the model.
voidpatchValue
voidPatches the value of a control.
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.
TValue{ onlySelf?: boolean | undefined; emitEvent?: boolean | undefined; emitModelToViewChange?: boolean | undefined; emitViewToModelChange?: boolean | undefined; } | undefinedvoidreset
voidResets 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.
// 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"
TValue | FormControlState<TValue> | undefinedResets the control with an initial value, or an object that defines the initial value and disabled state.
{ onlySelf?: boolean | undefined; emitEvent?: boolean | undefined; } | undefinedConfiguration 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 thestatusChangesandvalueChangesobservables emit events with the latest status and value when the control is reset. When false, no events are emitted.
voidgetRawValue
TValueFor a simple FormControl, the raw value is equivalent to the value.
TValueregisterOnChange
voidRegister a listener for change events.
FunctionThe method that is called when the value changes
voidregisterOnDisabledChange
voidRegister a listener for disabled events.
(isDisabled: boolean) => voidThe method that is called when the disabled status changes.
voidvalue
TValueThe 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 | nullReturns 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.
validator
ValidatorFn | nullasyncValidator
AsyncValidatorFn | nullReturns 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.
asyncValidator
AsyncValidatorFn | nullstatus
FormControlStatusThe validation status of the control.
valid
booleanA control is valid when its status is VALID.
invalid
booleanA control is invalid when its status is INVALID.
pending
booleanA control is pending when its status is PENDING.
disabled
booleanA 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.
enabled
booleanA control is enabled as long as its status is not DISABLED.
errors
ValidationErrors | nullAn object containing any errors generated by failing validation, or null if there are no errors.
pristine
booleanA control is pristine if the user has not yet changed
the value in the UI.
dirty
booleanA control is dirty if the user has changed the value
in the UI.
touched
booleanTrue if the control is marked as touched.
A control is marked touched once the user has triggered
a blur event on it.
untouched
booleanTrue 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.
events
anyA multicasting observable that emits an event every time the state of the control changes. It emits for value, status, pristine or touched changes.
Note: On value change, the emit happens right after a value of this control is updated. The
value of a parent control (for example if this FormControl is a part of a FormGroup) is updated
later, so accessing a value of a parent control (using the value property) from the callback
of this event might result in getting a value that has not been updated yet. Subscribe to the
events of the parent control instead.
For other event types, the events are emitted after the parent control has been updated.
valueChanges
Observable<TValue>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.
Note: the emit happens right after a value of this control is updated. The value of a
parent control (for example if this FormControl is a part of a FormGroup) is updated later, so
accessing a value of a parent control (using the value property) from the callback of this
event might result in getting a value that has not been updated yet. Subscribe to the
valueChanges event of the parent control instead.
statusChanges
Observable<FormControlStatus>A multicasting observable that emits an event every time the validation status of the control
recalculates.
updateOn
FormHooksReports the update strategy of the AbstractControl (meaning
the event on which the control updates itself).
Possible values: 'change' | 'blur' | 'submit'
Default value: 'change'
setValidators
voidSets the synchronous validators that are active on this control. Calling this overwrites any existing synchronous validators.
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.
voidsetAsyncValidators
voidSets the asynchronous validators that are active on this control. Calling this overwrites any existing asynchronous validators.
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.
voidaddValidators
voidAdd a synchronous validator or validators to this control, without affecting other validators.
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.
ValidatorFn | ValidatorFn[]The new validator function or functions to add to this control.
voidaddAsyncValidators
voidAdd an asynchronous validator or validators to this control, without affecting other validators.
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.
AsyncValidatorFn | AsyncValidatorFn[]The new asynchronous validator function or functions to add to this control.
voidremoveValidators
voidRemove 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.
voidReference to a ValidatorFn
// Reference to the RequiredValidatorconst ctrl = new FormControl<string | null>('', Validators.required);ctrl.removeValidators(Validators.required);// Reference to anonymous function inside MinValidatorconst minValidator = Validators.min(3);const ctrl = new FormControl<string | null>('', minValidator);expect(ctrl.hasValidator(minValidator)).toEqual(true)expect(ctrl.hasValidator(Validators.min(3))).toEqual(false)ctrl.removeValidators(minValidator);
When you add or remove a validator at run time, you must call
updateValueAndValidity() for the new validation to take effect.
removeAsyncValidators
voidRemove 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.
When you add or remove a validator at run time, you must call
updateValueAndValidity() for the new validation to take effect.
AsyncValidatorFn | AsyncValidatorFn[]The asynchronous validator or validators to remove.
voidhasValidator
booleanCheck 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.
booleanReference to a ValidatorFn
// Reference to the RequiredValidatorconst ctrl = new FormControl<number | null>(0, Validators.required);expect(ctrl.hasValidator(Validators.required)).toEqual(true)// Reference to anonymous function inside MinValidatorconst minValidator = Validators.min(3);const ctrl = new FormControl<number | null>(0, minValidator);expect(ctrl.hasValidator(minValidator)).toEqual(true)expect(ctrl.hasValidator(Validators.min(3))).toEqual(false)
hasAsyncValidator
booleanCheck 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.
AsyncValidatorFnThe asynchronous validator to check for presence. Compared by function reference.
booleanclearValidators
voidEmpties out the synchronous validator list.
When you add or remove a validator at run time, you must call
updateValueAndValidity() for the new validation to take effect.
voidclearAsyncValidators
voidEmpties out the async validator list.
When you add or remove a validator at run time, you must call
updateValueAndValidity() for the new validation to take effect.
voidmarkAsTouched
2 overloadsMarks the control as touched. A control is touched by focus and
blur events that do not change the value.
{ onlySelf?: boolean | undefined; emitEvent?: boolean | undefined; } | undefinedConfiguration 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), theeventsobservable emits aTouchedChangeEventwith thetouchedproperty beingtrue. When false, no events are emitted.
void{ onlySelf?: boolean | undefined; emitEvent?: boolean | undefined; sourceControl?: AbstractControl<any, any, any> | undefined; } | undefinedvoidmarkAllAsDirty
voidMarks the control and all its descendant controls as dirty.
{ emitEvent?: boolean | undefined; }Configuration options that determine how the control propagates changes and emits events after marking is applied.
emitEvent: When true or not supplied (the default), theeventsobservable emits aPristineChangeEventwith thepristineproperty beingfalse. When false, no events are emitted.
voidmarkAllAsTouched
voidMarks the control and all its descendant controls as touched.
{ emitEvent?: boolean | undefined; }Configuration options that determine how the control propagates changes and emits events after marking is applied.
emitEvent: When true or not supplied (the default), theeventsobservable emits aTouchedChangeEventwith thetouchedproperty beingtrue. When false, no events are emitted.
voidmarkAsUntouched
2 overloadsMarks the control as untouched.
If the control has any children, also marks all children as untouched
and recalculates the touched status of all parent controls.
{ onlySelf?: boolean | undefined; emitEvent?: boolean | undefined; } | undefinedConfiguration 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.emitEvent: When true or not supplied (the default), theeventsobservable emits aTouchedChangeEventwith thetouchedproperty beingfalse. When false, no events are emitted.
void{ onlySelf?: boolean | undefined; emitEvent?: boolean | undefined; sourceControl?: AbstractControl<any, any, any> | undefined; }voidmarkAsDirty
2 overloadsMarks the control as dirty. A control becomes dirty when
the control's value is changed through the UI; compare markAsTouched.
{ onlySelf?: boolean | undefined; emitEvent?: boolean | undefined; } | undefinedConfiguration 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), theeventsobservable emits aPristineChangeEventwith thepristineproperty beingfalse. When false, no events are emitted.
void{ onlySelf?: boolean | undefined; emitEvent?: boolean | undefined; sourceControl?: AbstractControl<any, any, any> | undefined; }voidmarkAsPristine
2 overloadsMarks the control as pristine.
If the control has any children, marks all children as pristine,
and recalculates the pristine status of all parent
controls.
{ onlySelf?: boolean | undefined; emitEvent?: boolean | undefined; } | undefinedConfiguration 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.emitEvent: When true or not supplied (the default), theeventsobservable emits aPristineChangeEventwith thepristineproperty beingtrue. When false, no events are emitted.
void{ onlySelf?: boolean | undefined; emitEvent?: boolean | undefined; sourceControl?: AbstractControl<any, any, any> | undefined; }voidmarkAsPending
2 overloadsMarks the control as pending.
A control is pending while the control performs async validation.
{ onlySelf?: boolean | undefined; emitEvent?: boolean | undefined; } | undefinedConfiguration 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), thestatusChangesobservable emits an event with the latest status the control is marked pending and theeventsobservable emits aStatusChangeEventwith thestatusproperty beingPENDINGWhen false, no events are emitted.
void{ onlySelf?: boolean | undefined; emitEvent?: boolean | undefined; sourceControl?: AbstractControl<any, any, any> | undefined; }voiddisable
2 overloadsDisables the control. This means the control is exempt from validation checks and
excluded from the aggregate value of any parent. Its status is DISABLED.
If the control has children, all children are also disabled.
{ onlySelf?: boolean | undefined; emitEvent?: boolean | undefined; } | undefinedConfiguration 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), thestatusChanges,valueChangesandeventsobservables emit events with the latest status and value when the control is disabled. When false, no events are emitted.
void{ onlySelf?: boolean | undefined; emitEvent?: boolean | undefined; sourceControl?: AbstractControl<any, any, any> | undefined; }voidenable
voidEnables 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.
By default, if the control has children, all children are enabled.
{ onlySelf?: boolean | undefined; emitEvent?: boolean | undefined; }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), thestatusChanges,valueChangesandeventsobservables emit events with the latest status and value when the control is enabled. When false, no events are emitted.
voidsetParent
voidupdateValueAndValidity
2 overloadsRecalculates the value and validation status of the control.
By default, it also updates the value and validity of its ancestors.
{ onlySelf?: boolean | undefined; emitEvent?: boolean | undefined; } | undefinedConfiguration 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), thestatusChanges,valueChangesandeventsobservables emit events with the latest status and value when the control is updated. When false, no events are emitted.
void{ onlySelf?: boolean | undefined; emitEvent?: boolean | undefined; sourceControl?: AbstractControl<any, any, any> | undefined; }voidsetErrors
2 overloadsSets errors on a form control when running validations manually, rather than automatically.
Calling setErrors also updates the validity of the parent control.
Note: Manually set errors are always overwritten by the results of the next validation run.
{ emitEvent?: boolean | undefined; } | undefinedConfiguration options that determine how the control propagates changes and emits events after the control errors are set.
emitEvent: When true or not supplied (the default), thestatusChangesobservable emits an event after the errors are set.
voidManually 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);
{ emitEvent?: boolean | undefined; shouldHaveEmitted?: boolean | undefined; } | undefinedvoidget
2 overloadsRetrieves a child control given the control's name or path.
This signature for get supports strings and const arrays (.get(['foo', 'bar'] as const)).
PAbstractControl<ɵGetProperty<TRawValue, P>, ɵGetProperty<TRawValue, P>, any> | nullRetrieves a child control given the control's name or path.
This signature for get supports non-const (mutable) arrays. Inferred type
information will not be as robust, so prefer to pass a readonly array if possible.
PAbstractControl<ɵGetProperty<TRawValue, P>, ɵGetProperty<TRawValue, P>, any> | nullgetError
anyReports error data for the control with the given path.
stringThe code of the error to check
string | (string | number)[] | undefinedA list of control names that designates how to move from the current control to the control that should be queried for errors.
anyFor 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:
- An array of string control names, e.g.
['address', 'street'] - A period-delimited list of control names in one string, e.g.
'address.street'
hasError
booleanReports whether the control with the given path has the error specified.
stringThe code of the error to check
string | (string | number)[] | undefinedA list of control names that designates how to move from the current control to the control that should be queried for errors.
booleanFor 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:
- An array of string control names, e.g.
['address', 'street'] - 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.
root
AbstractControl<any, any, any>Retrieves the top-level ancestor of this control.
Description
Tracks the value and validation status of an individual form control.
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.
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'