@angular/forms
Version:
Angular - directives and services for creating forms
1,349 lines (1,325 loc) • 201 kB
TypeScript
/**
* @license Angular v17.3.5
* (c) 2010-2024 Google LLC. https://angular.io/
* License: MIT
*/
import { AfterViewInit } from '@angular/core';
import { ChangeDetectorRef } from '@angular/core';
import { ElementRef } from '@angular/core';
import { EventEmitter } from '@angular/core';
import * as i0 from '@angular/core';
import { InjectionToken } from '@angular/core';
import { Injector } from '@angular/core';
import { ModuleWithProviders } from '@angular/core';
import { Observable } from 'rxjs';
import { OnChanges } from '@angular/core';
import { OnDestroy } from '@angular/core';
import { OnInit } from '@angular/core';
import { Provider } from '@angular/core';
import { Renderer2 } from '@angular/core';
import { SimpleChanges } from '@angular/core';
import { Type } from '@angular/core';
import { Version } from '@angular/core';
/**
* This is the base class for `FormControl`, `FormGroup`, and `FormArray`.
*
* 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.
*
* The first type parameter TValue represents the value type of the control (`control.value`).
* The optional type parameter TRawValue represents the raw value type (`control.getRawValue()`).
*
* @see [Forms Guide](/guide/forms)
* @see [Reactive Forms Guide](/guide/reactive-forms)
* @see [Dynamic Forms Guide](/guide/dynamic-form)
*
* @publicApi
*/
export declare abstract class AbstractControl<TValue = any, TRawValue extends TValue = TValue> {
private _parent;
private _asyncValidationSubscription;
/**
* 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.
*
*/
readonly value: TValue;
/**
* Initialize the AbstractControl instance.
*
* @param validators The function or array of functions that is used to determine the validity of
* this control synchronously.
* @param asyncValidators The function or array of functions that is used to determine validity of
* this control asynchronously.
*/
constructor(validators: ValidatorFn | ValidatorFn[] | null, asyncValidators: AsyncValidatorFn | AsyncValidatorFn[] | 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.
*/
get validator(): ValidatorFn | null;
set validator(validatorFn: ValidatorFn | 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.
*/
get asyncValidator(): AsyncValidatorFn | null;
set asyncValidator(asyncValidatorFn: AsyncValidatorFn | null);
/**
* The parent control.
*/
get parent(): FormGroup | FormArray | null;
/**
* The validation status of the control.
*
* @see {@link FormControlStatus}
*
* These status values are mutually exclusive, so a control cannot be
* both valid AND invalid or invalid AND disabled.
*/
readonly status: FormControlStatus;
/**
* A control is `valid` when its `status` is `VALID`.
*
* @see {@link AbstractControl.status}
*
* @returns True if the control has passed all of its validation tests,
* false otherwise.
*/
get valid(): boolean;
/**
* A control is `invalid` when its `status` is `INVALID`.
*
* @see {@link AbstractControl.status}
*
* @returns True if this control has failed one or more of its validation checks,
* false otherwise.
*/
get invalid(): boolean;
/**
* A control is `pending` when its `status` is `PENDING`.
*
* @see {@link AbstractControl.status}
*
* @returns True if this control is in the process of conducting a validation check,
* false otherwise.
*/
get pending(): boolean;
/**
* 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 {@link AbstractControl.status}
*
* @returns True if the control is disabled, false otherwise.
*/
get disabled(): boolean;
/**
* A control is `enabled` as long as its `status` is not `DISABLED`.
*
* @returns True if the control has any status other than 'DISABLED',
* false if the status is 'DISABLED'.
*
* @see {@link AbstractControl.status}
*
*/
get enabled(): boolean;
/**
* An object containing any errors generated by failing validation,
* or null if there are no errors.
*/
readonly errors: ValidationErrors | null;
/**
* A control is `pristine` if the user has not yet changed
* the value in the UI.
*
* @returns True if the user has not yet changed the value in the UI; compare `dirty`.
* Programmatic changes to a control's value do not mark it dirty.
*/
readonly pristine: boolean;
/**
* A control is `dirty` if the user has changed the value
* in the UI.
*
* @returns True if the user has changed the value of this control in the UI; compare `pristine`.
* Programmatic changes to a control's value do not mark it dirty.
*/
get dirty(): boolean;
/**
* True if the control is marked as `touched`.
*
* A control is marked `touched` once the user has triggered
* a `blur` event on it.
*/
readonly touched: boolean;
/**
* 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.
*/
get untouched(): boolean;
/**
* 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.
*/
readonly valueChanges: Observable<TValue>;
/**
* A multicasting observable that emits an event every time the validation `status` of the control
* recalculates.
*
* @see {@link FormControlStatus}
* @see {@link AbstractControl.status}
*
*/
readonly statusChanges: Observable<FormControlStatus>;
/**
* Reports the update strategy of the `AbstractControl` (meaning
* the event on which the control updates itself).
* Possible values: `'change'` | `'blur'` | `'submit'`
* Default value: `'change'`
*/
get updateOn(): FormHooks;
/**
* Sets 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.
*/
setValidators(validators: ValidatorFn | ValidatorFn[] | null): void;
/**
* Sets 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.
*/
setAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[] | null): void;
/**
* Add 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.
*
* @param validators The new validator function or functions to add to this control.
*/
addValidators(validators: ValidatorFn | ValidatorFn[]): void;
/**
* Add 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.
*
* @param validators The new asynchronous validator function or functions to add to this control.
*/
addAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void;
/**
* 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.
*
* @usageNotes
*
* ### Reference to a ValidatorFn
*
* ```
* // Reference to the RequiredValidator
* const ctrl = new FormControl<string | null>('', Validators.required);
* ctrl.removeValidators(Validators.required);
*
* // Reference to anonymous function inside MinValidator
* const 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.
*
* @param validators The validator or validators to remove.
*/
removeValidators(validators: ValidatorFn | ValidatorFn[]): void;
/**
* 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.
*
* When you add or remove a validator at run time, you must call
* `updateValueAndValidity()` for the new validation to take effect.
*
* @param validators The asynchronous validator or validators to remove.
*/
removeAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void;
/**
* 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.
*
* @usageNotes
*
* ### Reference to a ValidatorFn
*
* ```
* // Reference to the RequiredValidator
* const ctrl = new FormControl<number | null>(0, Validators.required);
* expect(ctrl.hasValidator(Validators.required)).toEqual(true)
*
* // Reference to anonymous function inside MinValidator
* const 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)
* ```
*
* @param validator The validator to check for presence. Compared by function reference.
* @returns Whether the provided validator was found on this control.
*/
hasValidator(validator: ValidatorFn): boolean;
/**
* 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.
*
* @param validator The asynchronous validator to check for presence. Compared by function
* reference.
* @returns Whether the provided asynchronous validator was found on this control.
*/
hasAsyncValidator(validator: AsyncValidatorFn): boolean;
/**
* Empties 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.
*
*/
clearValidators(): void;
/**
* Empties 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.
*
*/
clearAsyncValidators(): void;
/**
* Marks the control as `touched`. A control is touched by focus and
* blur events that do not change the value.
*
* @see {@link markAsUntouched()}
* @see {@link markAsDirty()}
* @see {@link markAsPristine()}
*
* @param opts 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.
*/
markAsTouched(opts?: {
onlySelf?: boolean;
}): void;
/**
* Marks the control and all its descendant controls as `touched`.
* @see {@link markAsTouched()}
*/
markAllAsTouched(): void;
/**
* Marks 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.
*
* @see {@link markAsTouched()}
* @see {@link markAsDirty()}
* @see {@link markAsPristine()}
*
* @param opts 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.
*/
markAsUntouched(opts?: {
onlySelf?: boolean;
}): void;
/**
* Marks the control as `dirty`. A control becomes dirty when
* the control's value is changed through the UI; compare `markAsTouched`.
*
* @see {@link markAsTouched()}
* @see {@link markAsUntouched()}
* @see {@link markAsPristine()}
*
* @param opts 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.
*/
markAsDirty(opts?: {
onlySelf?: boolean;
}): void;
/**
* Marks the control as `pristine`.
*
* If the control has any children, marks all children as `pristine`,
* and recalculates the `pristine` status of all parent
* controls.
*
* @see {@link markAsTouched()}
* @see {@link markAsUntouched()}
* @see {@link markAsDirty()}
*
* @param opts 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.
*/
markAsPristine(opts?: {
onlySelf?: boolean;
}): void;
/**
* Marks the control as `pending`.
*
* A control is pending while the control performs async validation.
*
* @see {@link AbstractControl.status}
*
* @param opts 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.
*
*/
markAsPending(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
/**
* 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`.
*
* If the control has children, all children are also disabled.
*
* @see {@link AbstractControl.status}
*
* @param opts 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.
*/
disable(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
/**
* 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.
*
* By default, if the control has children, all children are enabled.
*
* @see {@link AbstractControl.status}
*
* @param opts 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.
*/
enable(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
private _updateAncestors;
/**
* Sets the parent of the control
*
* @param parent The new parent.
*/
setParent(parent: FormGroup | FormArray | null): void;
/**
* Sets the value of the control. Abstract method (implemented in sub-classes).
*/
abstract setValue(value: TRawValue, options?: Object): void;
/**
* Patches the value of the control. Abstract method (implemented in sub-classes).
*/
abstract patchValue(value: TValue, options?: Object): void;
/**
* Resets the control. Abstract method (implemented in sub-classes).
*/
abstract reset(value?: TValue, options?: Object): void;
/**
* The raw value of this control. For most control implementations, the raw value will include
* disabled children.
*/
getRawValue(): any;
/**
* Recalculates the value and validation status of the control.
*
* By default, it also updates the value and validity of its ancestors.
*
* @param opts 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.
*/
updateValueAndValidity(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
private _setInitialStatus;
private _runValidator;
private _runAsyncValidator;
private _cancelExistingSubscription;
/**
* Sets errors on a form control when running validations manually, rather than automatically.
*
* Calling `setErrors` also updates the validity of the parent control.
*
* @param opts Configuration 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), the `statusChanges`
* observable emits an event after the errors are set.
*
* @usageNotes
*
* ### 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);
* ```
*/
setErrors(errors: ValidationErrors | null, opts?: {
emitEvent?: boolean;
}): void;
/**
* Retrieves a child control given the control's name or path.
*
* This signature for get supports strings and `const` arrays (`.get(['foo', 'bar'] as const)`).
*/
get<P extends string | (readonly (string | number)[])>(path: P): AbstractControl<ɵGetProperty<TRawValue, P>> | null;
/**
* Retrieves 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.
*/
get<P extends string | Array<string | number>>(path: P): AbstractControl<ɵGetProperty<TRawValue, P>> | null;
/**
* @description
* Reports error data for the control with the given path.
*
* @param errorCode The code of the error to check
* @param path A list of control names that designates how to move from the current control
* to the control that should be queried for errors.
*
* @usageNotes
* 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']`
* 1. A period-delimited list of control names in one string, e.g. `'address.street'`
*
* @returns error data for that particular error. If the control or error is not present,
* null is returned.
*/
getError(errorCode: string, path?: Array<string | number> | string): any;
/**
* @description
* Reports whether the control with the given path has the error specified.
*
* @param errorCode The code of the error to check
* @param path A list of control names that designates how to move from the current control
* to the control that should be queried for errors.
*
* @usageNotes
* 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']`
* 1. 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.
*
* @returns whether the given error is present in the control at the given path.
*
* If the control is not present, false is returned.
*/
hasError(errorCode: string, path?: Array<string | number> | string): boolean;
/**
* Retrieves the top-level ancestor of this control.
*/
get root(): AbstractControl;
private _calculateStatus;
/**
* Internal implementation of the `setValidators` method. Needs to be separated out into a
* different method, because it is called in the constructor and it can break cases where
* a control is extended.
*/
private _assignValidators;
/**
* Internal implementation of the `setAsyncValidators` method. Needs to be separated out into a
* different method, because it is called in the constructor and it can break cases where
* a control is extended.
*/
private _assignAsyncValidators;
}
/**
* @description
* Base class for control directives.
*
* This class is only used internally in the `ReactiveFormsModule` and the `FormsModule`.
*
* @publicApi
*/
export declare abstract class AbstractControlDirective {
/**
* @description
* A reference to the underlying control.
*
* @returns the control that backs this directive. Most properties fall through to that instance.
*/
abstract get control(): AbstractControl | null;
/**
* @description
* Reports the value of the control if it is present, otherwise null.
*/
get value(): any;
/**
* @description
* Reports whether the control is valid. A control is considered valid if no
* validation errors exist with the current value.
* If the control is not present, null is returned.
*/
get valid(): boolean | null;
/**
* @description
* Reports whether the control is invalid, meaning that an error exists in the input value.
* If the control is not present, null is returned.
*/
get invalid(): boolean | null;
/**
* @description
* Reports whether a control is pending, meaning that async validation is occurring and
* errors are not yet available for the input value. If the control is not present, null is
* returned.
*/
get pending(): boolean | null;
/**
* @description
* Reports whether the control is disabled, meaning that the control is disabled
* in the UI and is exempt from validation checks and excluded from aggregate
* values of ancestor controls. If the control is not present, null is returned.
*/
get disabled(): boolean | null;
/**
* @description
* Reports whether the control is enabled, meaning that the control is included in ancestor
* calculations of validity or value. If the control is not present, null is returned.
*/
get enabled(): boolean | null;
/**
* @description
* Reports the control's validation errors. If the control is not present, null is returned.
*/
get errors(): ValidationErrors | null;
/**
* @description
* Reports whether the control is pristine, meaning that the user has not yet changed
* the value in the UI. If the control is not present, null is returned.
*/
get pristine(): boolean | null;
/**
* @description
* Reports whether the control is dirty, meaning that the user has changed
* the value in the UI. If the control is not present, null is returned.
*/
get dirty(): boolean | null;
/**
* @description
* Reports whether the control is touched, meaning that the user has triggered
* a `blur` event on it. If the control is not present, null is returned.
*/
get touched(): boolean | null;
/**
* @description
* Reports the validation status of the control. Possible values include:
* 'VALID', 'INVALID', 'DISABLED', and 'PENDING'.
* If the control is not present, null is returned.
*/
get status(): string | null;
/**
* @description
* Reports whether the control is untouched, meaning that the user has not yet triggered
* a `blur` event on it. If the control is not present, null is returned.
*/
get untouched(): boolean | null;
/**
* @description
* Returns a multicasting observable that emits a validation status whenever it is
* calculated for the control. If the control is not present, null is returned.
*/
get statusChanges(): Observable<any> | null;
/**
* @description
* Returns a multicasting observable of value changes for the control that emits every time the
* value of the control changes in the UI or programmatically.
* If the control is not present, null is returned.
*/
get valueChanges(): Observable<any> | null;
/**
* @description
* Returns an array that represents the path from the top-level form to this control.
* Each index is the string name of the control on that level.
*/
get path(): string[] | null;
/**
* Contains the result of merging synchronous validators into a single validator function
* (combined using `Validators.compose`).
*/
private _composedValidatorFn;
/**
* Contains the result of merging asynchronous validators into a single validator function
* (combined using `Validators.composeAsync`).
*/
private _composedAsyncValidatorFn;
/**
* @description
* Synchronous validator function composed of all the synchronous validators registered with this
* directive.
*/
get validator(): ValidatorFn | null;
/**
* @description
* Asynchronous validator function composed of all the asynchronous validators registered with
* this directive.
*/
get asyncValidator(): AsyncValidatorFn | null;
private _onDestroyCallbacks;
/**
* @description
* Resets the control with the provided value if the control is present.
*/
reset(value?: any): void;
/**
* @description
* Reports whether the control with the given path has the error specified.
*
* @param errorCode The code of the error to check
* @param path A list of control names that designates how to move from the current control
* to the control that should be queried for errors.
*
* @usageNotes
* 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']`
* 1. 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.
*
* @returns whether the given error is present in the control at the given path.
*
* If the control is not present, false is returned.
*/
hasError(errorCode: string, path?: Array<string | number> | string): boolean;
/**
* @description
* Reports error data for the control with the given path.
*
* @param errorCode The code of the error to check
* @param path A list of control names that designates how to move from the current control
* to the control that should be queried for errors.
*
* @usageNotes
* 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']`
* 1. A period-delimited list of control names in one string, e.g. `'address.street'`
*
* @returns error data for that particular error. If the control or error is not present,
* null is returned.
*/
getError(errorCode: string, path?: Array<string | number> | string): any;
}
/**
* Interface for options provided to an `AbstractControl`.
*
* @publicApi
*/
export declare interface AbstractControlOptions {
/**
* @description
* The list of validators applied to a control.
*/
validators?: ValidatorFn | ValidatorFn[] | null;
/**
* @description
* The list of async validators applied to control.
*/
asyncValidators?: AsyncValidatorFn | AsyncValidatorFn[] | null;
/**
* @description
* The event name for control to update upon.
*/
updateOn?: 'change' | 'blur' | 'submit';
}
declare class AbstractControlStatus {
private _cd;
constructor(cd: AbstractControlDirective | null);
protected get isTouched(): boolean;
protected get isUntouched(): boolean;
protected get isPristine(): boolean;
protected get isDirty(): boolean;
protected get isValid(): boolean;
protected get isInvalid(): boolean;
protected get isPending(): boolean;
protected get isSubmitted(): boolean;
}
/**
* @description
* A base class for code shared between the `NgModelGroup` and `FormGroupName` directives.
*
* @publicApi
*/
export declare class AbstractFormGroupDirective extends ControlContainer implements OnInit, OnDestroy {
/** @nodoc */
ngOnInit(): void;
/** @nodoc */
ngOnDestroy(): void;
/**
* @description
* The `FormGroup` bound to this directive.
*/
get control(): FormGroup;
/**
* @description
* The path to this group from the top-level directive.
*/
get path(): string[];
/**
* @description
* The top-level directive for this group if present, otherwise null.
*/
get formDirective(): Form | null;
static ɵfac: i0.ɵɵFactoryDeclaration<AbstractFormGroupDirective, never>;
static ɵdir: i0.ɵɵDirectiveDeclaration<AbstractFormGroupDirective, never, never, {}, {}, never, never, false, never>;
}
/**
* A base class for Validator-based Directives. The class contains common logic shared across such
* Directives.
*
* For internal use only, this class is not intended for use outside of the Forms package.
*/
declare abstract class AbstractValidatorDirective implements Validator, OnChanges {
private _validator;
private _onChange;
/** @nodoc */
ngOnChanges(changes: SimpleChanges): void;
/** @nodoc */
validate(control: AbstractControl): ValidationErrors | null;
/** @nodoc */
registerOnValidatorChange(fn: () => void): void;
/**
* @description
* Determines whether this validator should be active or not based on an input.
* Base class implementation checks whether an input is defined (if the value is different from
* `null` and `undefined`). Validator classes that extend this base class can override this
* function with the logic specific to a particular validator directive.
*/
enabled(input: unknown): boolean;
static ɵfac: i0.ɵɵFactoryDeclaration<AbstractValidatorDirective, never>;
static ɵdir: i0.ɵɵDirectiveDeclaration<AbstractValidatorDirective, never, never, {}, {}, never, never, false, never>;
}
/**
* @description
* An interface implemented by classes that perform asynchronous validation.
*
* @usageNotes
*
* ### Provide a custom async validator directive
*
* The following example implements the `AsyncValidator` interface to create an
* async validator directive with a custom error key.
*
* ```typescript
* import { of } from 'rxjs';
*
* @Directive({
* selector: '[customAsyncValidator]',
* providers: [{provide: NG_ASYNC_VALIDATORS, useExisting: CustomAsyncValidatorDirective, multi:
* true}]
* })
* class CustomAsyncValidatorDirective implements AsyncValidator {
* validate(control: AbstractControl): Observable<ValidationErrors|null> {
* return of({'custom': true});
* }
* }
* ```
*
* @publicApi
*/
export declare interface AsyncValidator extends Validator {
/**
* @description
* Method that performs async validation against the provided control.
*
* @param control The control to validate against.
*
* @returns A promise or observable that resolves a map of validation errors
* if validation fails, otherwise null.
*/
validate(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>;
}
/**
* @description
* A function that receives a control and returns a Promise or observable
* that emits validation errors if present, otherwise null.
*
* @publicApi
*/
export declare interface AsyncValidatorFn {
(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>;
}
/**
* Base class for all ControlValueAccessor classes defined in Forms package.
* Contains common logic and utility functions.
*
* Note: this is an *internal-only* class and should not be extended or used directly in
* applications code.
*/
declare class BaseControlValueAccessor {
private _renderer;
private _elementRef;
/**
* The registered callback function called when a change or input event occurs on the input
* element.
* @nodoc
*/
onChange: (_: any) => void;
/**
* The registered callback function called when a blur event occurs on the input element.
* @nodoc
*/
onTouched: () => void;
constructor(_renderer: Renderer2, _elementRef: ElementRef);
/**
* Helper method that sets a property on a target element using the current Renderer
* implementation.
* @nodoc
*/
protected setProperty(key: string, value: any): void;
/**
* Registers a function called when the control is touched.
* @nodoc
*/
registerOnTouched(fn: () => void): void;
/**
* Registers a function called when the control value changes.
* @nodoc
*/
registerOnChange(fn: (_: any) => {}): void;
/**
* Sets the "disabled" property on the range input element.
* @nodoc
*/
setDisabledState(isDisabled: boolean): void;
static ɵfac: i0.ɵɵFactoryDeclaration<BaseControlValueAccessor, never>;
static ɵdir: i0.ɵɵDirectiveDeclaration<BaseControlValueAccessor, never, never, {}, {}, never, never, false, never>;
}
/**
* Base class for all built-in ControlValueAccessor classes (except DefaultValueAccessor, which is
* used in case no other CVAs can be found). We use this class to distinguish between default CVA,
* built-in CVAs and custom CVAs, so that Forms logic can recognize built-in CVAs and treat custom
* ones with higher priority (when both built-in and custom CVAs are present).
*
* Note: this is an *internal-only* class and should not be extended or used directly in
* applications code.
*/
declare class BuiltInControlValueAccessor extends BaseControlValueAccessor {
static ɵfac: i0.ɵɵFactoryDeclaration<BuiltInControlValueAccessor, never>;
static ɵdir: i0.ɵɵDirectiveDeclaration<BuiltInControlValueAccessor, never, never, {}, {}, never, never, false, never>;
}
/**
* Token to provide to allow SetDisabledState to always be called when a CVA is added, regardless of
* whether the control is disabled or enabled.
*
* @see {@link FormsModule#withconfig}
*/
declare const CALL_SET_DISABLED_STATE: InjectionToken<SetDisabledStateOption>;
/**
* @description
* Provider which adds `CheckboxRequiredValidator` to the `NG_VALIDATORS` multi-provider list.
*/
declare const CHECKBOX_REQUIRED_VALIDATOR: Provider;
/**
* @description
* A `ControlValueAccessor` for writing a value and listening to changes on a checkbox input
* element.
*
* @usageNotes
*
* ### Using a checkbox with a reactive form.
*
* The following example shows how to use a checkbox with a reactive form.
*
* ```ts
* const rememberLoginControl = new FormControl();
* ```
*
* ```
* <input type="checkbox" [formControl]="rememberLoginControl">
* ```
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
export declare class CheckboxControlValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor {
/**
* Sets the "checked" property on the input element.
* @nodoc
*/
writeValue(value: any): void;
static ɵfac: i0.ɵɵFactoryDeclaration<CheckboxControlValueAccessor, never>;
static ɵdir: i0.ɵɵDirectiveDeclaration<CheckboxControlValueAccessor, "input[type=checkbox][formControlName],input[type=checkbox][formControl],input[type=checkbox][ngModel]", never, {}, {}, never, never, false, never>;
}
/**
* A Directive that adds the `required` validator to checkbox controls marked with the
* `required` attribute. The directive is provided with the `NG_VALIDATORS` multi-provider list.
*
* @see [Form Validation](guide/form-validation)
*
* @usageNotes
*
* ### Adding a required checkbox validator using template-driven forms
*
* The following example shows how to add a checkbox required validator to an input attached to an
* ngModel binding.
*
* ```
* <input type="checkbox" name="active" ngModel required>
* ```
*
* @publicApi
* @ngModule FormsModule
* @ngModule ReactiveFormsModule
*/
export declare class CheckboxRequiredValidator extends RequiredValidator {
static ɵfac: i0.ɵɵFactoryDeclaration<CheckboxRequiredValidator, never>;
static ɵdir: i0.ɵɵDirectiveDeclaration<CheckboxRequiredValidator, "input[type=checkbox][required][formControlName],input[type=checkbox][required][formControl],input[type=checkbox][required][ngModel]", never, {}, {}, never, never, false, never>;
}
/**
* @description
* Provide this token to control if form directives buffer IME input until
* the "compositionend" event occurs.
* @publicApi
*/
export declare const COMPOSITION_BUFFER_MODE: InjectionToken<boolean>;
/**
* ControlConfig<T> is a tuple containing a value of type T, plus optional validators and async
* validators.
*
* @publicApi
*/
export declare type ControlConfig<T> = [T | FormControlState<T>, (ValidatorFn | (ValidatorFn[]))?, (AsyncValidatorFn | AsyncValidatorFn[])?];
/**
* @description
* A base class for directives that contain multiple registered instances of `NgControl`.
* Only used by the forms module.
*
* @publicApi
*/
export declare abstract class ControlContainer extends AbstractControlDirective {
/**
* @description
* The name for the control
*/
name: string | number | null;
/**
* @description
* The top-level form directive for the control.
*/
get formDirective(): Form | null;
/**
* @description
* The path to this group.
*/
get path(): string[] | null;
}
/**
* @description
* Defines an interface that acts as a bridge between the Angular forms API and a
* native element in the DOM.
*
* Implement this interface to create a custom form control directive
* that integrates with Angular forms.
*
* @see {@link DefaultValueAccessor}
*
* @publicApi
*/
export declare interface ControlValueAccessor {
/**
* @description
* Writes a new value to the element.
*
* This method is called by the forms API to write to the view when programmatic
* changes from model to view are requested.
*
* @usageNotes
* ### Write a value to the element
*
* The following example writes a value to the native DOM element.
*
* ```ts
* writeValue(value: any): void {
* this._renderer.setProperty(this._elementRef.nativeElement, 'value', value);
* }
* ```
*
* @param obj The new value for the element
*/
writeValue(obj: any): void;
/**
* @description
* Registers a callback function that is called when the control's value
* changes in the UI.
*
* This method is called by the forms API on initialization to update the form
* model when values propagate from the view to the model.
*
* When implementing the `registerOnChange` method in your own value accessor,
* save the given function so your class calls it at the appropriate time.
*
* @usageNotes
* ### Store the change function
*
* The following example stores the provided function as an internal method.
*
* ```ts
* registerOnChange(fn: (_: any) => void): void {
* this._onChange = fn;
* }
* ```
*
* When the value changes in the UI, call the registered
* function to allow the forms API to update itself:
*
* ```ts
* host: {
* '(change)': '_onChange($event.target.value)'
* }
* ```
*
* @param fn The callback function to register
*/
registerOnChange(fn: any): void;
/**
* @description
* Registers a callback function that is called by the forms API on initialization
* to update the form model on blur.
*
* When implementing `registerOnTouched` in your own value accessor, save the given
* function so your class calls it when the control should be considered
* blurred or "touched".
*
* @usageNotes
* ### Store the callback function
*
* The following example stores the provided function as an internal method.
*
* ```ts
* registerOnTouched(fn: any): void {
* this._onTouched = fn;
* }
* ```
*
* On blur (or equivalent), your class should call the registered function to allow
* the forms API to update itself:
*
* ```ts
* host: {
* '(blur)': '_onTouched()'
* }
* ```
*
* @param fn The callback function to register
*/
registerOnTouched(fn: any): void;
/**
* @description
* Function that is called by the forms API when the control status changes to
* or from 'DISABLED'. Depending on the status, it enables or disables the
* appropriate DOM element.
*
* @usageNotes
* The following is an example of writing the disabled property to a native DOM element:
*
* ```ts
* setDisabledState(isDisabled: boolean): void {
* this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
* }
* ```
*
* @param isDisabled The disabled status to set on the element
*/
setDisabledState?(isDisabled: boolean): void;
}
declare const DEFAULT_VALUE_ACCESSOR: Provider;
/**
* The default `ControlValueAccessor` for writing a value and listening to changes on input
* elements. The accessor is used by the `FormControlDirective`, `FormControlName`, and
* `NgModel` directives.
*
* {@searchKeywords ngDefaultControl}
*
* @usageNotes
*
* ### Using the default value accessor
*
* The following example shows how to use an input element that activates the default value accessor
* (in this case, a text field).
*
* ```ts
* const firstNameControl = new FormControl();
* ```
*
* ```
* <input type="text" [formControl]="firstNameControl">
* ```
*
* This value accessor is used by default for `<input type="text">` and `<textarea>` elements, but
* you could also use it for custom components that have similar behavior and do not require special
* processing. In order to attach the default value accessor to a custom element, add the
* `ngDefaultControl` attribute as shown below.
*
* ```
* <custom-input-component ngDefaultControl [(ngModel)]="value"></custom-input-component>
* ```
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
export declare class DefaultValueAccessor extends BaseControlValueAccessor implements ControlValueAccessor {
private _compositionMode;
/** Whether the user is creating a composition string (IME events). */
private _composing;
constructor(renderer: Renderer2, elementRef: ElementRef, _compositionMode: boolean);
/**
* Sets the "value" property on the input element.
* @nodoc
*/
writeValue(value: any): void;
static ɵfac: i0.ɵɵFactoryDeclaration<DefaultValueAccessor, [null, null, { optional: true; }]>;
static ɵdir: i0.ɵɵDirectiveDeclaration<DefaultValueAccessor, "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]", never, {}, {}, never, never, false, never>;
}
/**
* @description
* Provider which adds `EmailValidator` to the `NG_VALIDATORS` multi-provider list.
*/
declare const EMAIL_VALIDATOR: any;
/**
* A directive that adds the `email` validator to controls marked with the
* `email` attribute. The directive is provided with the `NG_VALIDATORS` multi-provider list.
*
* The email validation is based on the WHATWG HTML specification with some enhancements to
* incorporate more RFC rules. More information can be found