@angular/forms
Version:
Angular - directives and services for creating forms
1,439 lines (1,423 loc) • 149 kB
TypeScript
/**
* @license Angular v10.0.1
* (c) 2010-2020 Google LLC. https://angular.io/
* License: MIT
*/
import { AfterViewInit } from '@angular/core';
import { ElementRef } from '@angular/core';
import { EventEmitter } 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 { Renderer2 } from '@angular/core';
import { SimpleChanges } from '@angular/core';
import { StaticProvider } 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.
*
* @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 {
validator: ValidatorFn | null;
asyncValidator: AsyncValidatorFn | null;
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: any;
/**
* Initialize the AbstractControl instance.
*
* @param validator The function that determines the synchronous validity of this control.
* @param asyncValidator The function that determines the asynchronous validity of this
* control.
*/
constructor(validator: ValidatorFn | null, asyncValidator: AsyncValidatorFn | null);
/**
* The parent control.
*/
get parent(): FormGroup | FormArray;
/**
* 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.
*/
readonly status: string;
/**
* 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.
*/
readonly valueChanges: Observable<any>;
/**
* A multicasting observable that emits an event every time the validation `status` of the control
* recalculates.
*
* @see {@link AbstractControl.status}
*
*/
readonly statusChanges: Observable<any>;
/**
* 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 sync validators.
*
* When you add or remove a validator at run time, you must call
* `updateValueAndValidity()` for the new validation to take effect.
*
*/
setValidators(newValidator: ValidatorFn | ValidatorFn[] | null): void;
/**
* Sets the async validators that are active on this control. Calling this
* overwrites any existing async validators.
*
* When you add or remove a validator at run time, you must call
* `updateValueAndValidity()` for the new validation to take effect.
*
*/
setAsyncValidators(newValidator: AsyncValidatorFn | AsyncValidatorFn[] | null): void;
/**
* Empties out the sync 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 `markAsUntouched()`
* @see `markAsDirty()`
* @see `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 `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 `markAsTouched()`
* @see `markAsDirty()`
* @see `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 `markAsTouched()`
* @see `markAsUntouched()`
* @see `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 `markAsTouched()`
* @see `markAsUntouched()`
* @see `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;
/**
* @param parent Sets the parent of the control
*/
setParent(parent: FormGroup | FormArray): void;
/**
* Sets the value of the control. Abstract method (implemented in sub-classes).
*/
abstract setValue(value: any, options?: Object): void;
/**
* Patches the value of the control. Abstract method (implemented in sub-classes).
*/
abstract patchValue(value: any, options?: Object): void;
/**
* Resets the control. Abstract method (implemented in sub-classes).
*/
abstract reset(value?: any, options?: Object): void;
/**
* 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.
*
* @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.
*
* @param path A dot-delimited string or array of string/number values that define the path to the
* control.
*
* @usageNotes
* ### 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']);`
*/
get(path: Array<string | number> | string): AbstractControl | 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;
}
/**
* @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 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;
/**
* @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';
}
/**
* @description
* A base class for code shared between the `NgModelGroup` and `FormGroupName` directives.
*
* @publicApi
*/
export declare class AbstractFormGroupDirective extends ControlContainer implements OnInit, OnDestroy {
/**
* @description
* An internal callback method triggered on the instance after the inputs are set.
* Registers the group with its parent group.
*/
ngOnInit(): void;
/**
* @description
* An internal callback method triggered before the instance is destroyed.
* Removes the group from its parent group.
*/
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;
/**
* @description
* The synchronous validators registered with this group.
*/
get validator(): ValidatorFn | null;
/**
* @description
* The async validators registered with this group.
*/
get asyncValidator(): AsyncValidatorFn | null;
}
/**
* @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>;
}
/**
* @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 implements ControlValueAccessor {
private _renderer;
private _elementRef;
/**
* @description
* The registered callback function called when a change event occurs on the input element.
*/
onChange: (_: any) => void;
/**
* @description
* The registered callback function called when a blur event occurs on the input element.
*/
onTouched: () => void;
constructor(_renderer: Renderer2, _elementRef: ElementRef);
/**
* Sets the "checked" property on the input element.
*
* @param value The checked value
*/
writeValue(value: any): void;
/**
* @description
* Registers a function called when the control value changes.
*
* @param fn The callback function
*/
registerOnChange(fn: (_: any) => {}): void;
/**
* @description
* Registers a function called when the control is touched.
*
* @param fn The callback function
*/
registerOnTouched(fn: () => {}): void;
/**
* Sets the "disabled" property on the input element.
*
* @param isDisabled The disabled value
*/
setDisabledState(isDisabled: boolean): void;
}
/**
* 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 {
/**
* @description
* Method that validates whether or not the checkbox has been checked.
* Returns the validation result if enabled, otherwise null.
*/
validate(control: AbstractControl): ValidationErrors | null;
}
/**
* @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>;
/**
* @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 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;
}
/**
* @description
* 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.
*
* @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">
* ```
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
export declare class DefaultValueAccessor implements ControlValueAccessor {
private _renderer;
private _elementRef;
private _compositionMode;
/**
* @description
* The registered callback function called when an input event occurs on the input element.
*/
onChange: (_: any) => void;
/**
* @description
* The registered callback function called when a blur event occurs on the input element.
*/
onTouched: () => void;
/** 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.
*
* @param value The checked value
*/
writeValue(value: any): void;
/**
* @description
* Registers a function called when the control value changes.
*
* @param fn The callback function
*/
registerOnChange(fn: (_: any) => void): void;
/**
* @description
* Registers a function called when the control is touched.
*
* @param fn The callback function
*/
registerOnTouched(fn: () => void): void;
/**
* Sets the "disabled" property on the input element.
*
* @param isDisabled The disabled value
*/
setDisabledState(isDisabled: boolean): void;
}
/**
* 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.
*
* @see [Form Validation](guide/form-validation)
*
* @usageNotes
*
* ### Adding an email validator
*
* The following example shows how to add an email validator to an input attached to an ngModel
* binding.
*
* ```
* <input type="email" name="email" ngModel email>
* <input type="email" name="email" ngModel email="true">
* <input type="email" name="email" ngModel [email]="true">
* ```
*
* @publicApi
* @ngModule FormsModule
* @ngModule ReactiveFormsModule
*/
export declare class EmailValidator implements Validator {
private _enabled;
private _onChange;
/**
* @description
* Tracks changes to the email attribute bound to this directive.
*/
set email(value: boolean | string);
/**
* @description
* Method that validates whether an email address is valid.
* Returns the validation result if enabled, otherwise null.
*/
validate(control: AbstractControl): ValidationErrors | null;
/**
* @description
* Registers a callback function to call when the validator inputs change.
*
* @param fn The callback function
*/
registerOnValidatorChange(fn: () => void): void;
}
/**
* @description
* An interface implemented by `FormGroupDirective` and `NgForm` directives.
*
* Only used by the `ReactiveFormsModule` and `FormsModule`.
*
* @publicApi
*/
export declare interface Form {
/**
* @description
* Add a control to this form.
*
* @param dir The control directive to add to the form.
*/
addControl(dir: NgControl): void;
/**
* @description
* Remove a control from this form.
*
* @param dir: The control directive to remove from the form.
*/
removeControl(dir: NgControl): void;
/**
* @description
* The control directive from which to get the `FormControl`.
*
* @param dir: The control directive.
*/
getControl(dir: NgControl): FormControl;
/**
* @description
* Add a group of controls to this form.
*
* @param dir: The control group directive to add.
*/
addFormGroup(dir: AbstractFormGroupDirective): void;
/**
* @description
* Remove a group of controls to this form.
*
* @param dir: The control group directive to remove.
*/
removeFormGroup(dir: AbstractFormGroupDirective): void;
/**
* @description
* The `FormGroup` associated with a particular `AbstractFormGroupDirective`.
*
* @param dir: The form group directive from which to get the `FormGroup`.
*/
getFormGroup(dir: AbstractFormGroupDirective): FormGroup;
/**
* @description
* Update the model for a particular control with a new value.
*
* @param dir: The control directive to update.
* @param value: The new value for the control.
*/
updateModel(dir: NgControl, value: any): void;
}
/**
* Tracks the value and validity state of an array of `FormControl`,
* `FormGroup` or `FormArray` instances.
*
* A `FormArray` aggregates the values of each child `FormControl` into an array.
* It calculates its status by reducing the status values of its children. For example, if one of
* the controls in a `FormArray` is invalid, the entire array becomes invalid.
*
* `FormArray` is one of the three fundamental building blocks used to define forms in Angular,
* along with `FormControl` and `FormGroup`.
*
* @usageNotes
*
* ### Create an array of form controls
*
* ```
* const arr = new FormArray([
* new FormControl('Nancy', Validators.minLength(2)),
* new FormControl('Drew'),
* ]);
*
* console.log(arr.value); // ['Nancy', 'Drew']
* console.log(arr.status); // 'VALID'
* ```
*
* ### Create a form array with array-level validators
*
* You include array-level validators and async validators. These come in handy
* when you want to perform validation that considers the value of more than one child
* control.
*
* The two types of validators are passed in separately as the second and third arg
* respectively, or together as part of an options object.
*
* ```
* const arr = new FormArray([
* new FormControl('Nancy'),
* new FormControl('Drew')
* ], {validators: myValidator, asyncValidators: myAsyncValidator});
* ```
*
* ### Set the updateOn property for all controls in a form array
*
* The options object is used to set a default value for each child
* control's `updateOn` property. If you set `updateOn` to `'blur'` at the
* array level, all child controls default to 'blur', unless the child
* has explicitly specified a different `updateOn` value.
*
* ```ts
* const arr = new FormArray([
* new FormControl()
* ], {updateOn: 'blur'});
* ```
*
* ### Adding or removing controls from a form array
*
* To change the controls in the array, use the `push`, `insert`, `removeAt` or `clear` methods
* in `FormArray` itself. These methods ensure the controls are properly tracked in the
* form's hierarchy. Do not modify the array of `AbstractControl`s used to instantiate
* the `FormArray` directly, as that result in strange and unexpected behavior such
* as broken change detection.
*
* @publicApi
*/
export declare class FormArray extends AbstractControl {
controls: AbstractControl[];
/**
* Creates a new `FormArray` instance.
*
* @param controls An array of child controls. Each child control is given an index
* where it is registered.
*
* @param validatorOrOpts A synchronous validator function, or an array of
* such functions, or an `AbstractControlOptions` object that contains validation functions
* and a validation trigger.
*
* @param asyncValidator A single async validator or array of async validator functions
*
*/
constructor(controls: AbstractControl[], validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null);
/**
* Get the `AbstractControl` at the given `index` in the array.
*
* @param index Index in the array to retrieve the control
*/
at(index: number): AbstractControl;
/**
* Insert a new `AbstractControl` at the end of the array.
*
* @param control Form control to be inserted
*/
push(control: AbstractControl): void;
/**
* Insert a new `AbstractControl` at the given `index` in the array.
*
* @param index Index in the array to insert the control
* @param control Form control to be inserted
*/
insert(index: number, control: AbstractControl): void;
/**
* Remove the control at the given `index` in the array.
*
* @param index Index in the array to remove the control
*/
removeAt(index: number): void;
/**
* Replace an existing control.
*
* @param index Index in the array to replace the control
* @param control The `AbstractControl` control to replace the existing control
*/
setControl(index: number, control: AbstractControl): void;
/**
* Length of the control array.
*/
get length(): number;
/**
* Sets the value of the `FormArray`. It accepts an array that matches
* the structure of the control.
*
* This method performs strict checks, and throws an error if you try
* to set the value of a control that doesn't exist or if you exclude the
* value of a control.
*
* @usageNotes
* ### Set the values for the controls in the form array
*
* ```
* const arr = new FormArray([
* new FormControl(),
* new FormControl()
* ]);
* console.log(arr.value); // [null, null]
*
* arr.setValue(['Nancy', 'Drew']);
* console.log(arr.value); // ['Nancy', 'Drew']
* ```
*
* @param value Array of values for the controls
* @param options Configure 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 value is updated.
* When false, no events are emitted.
* The configuration options are passed to the {@link AbstractControl#updateValueAndValidity
* updateValueAndValidity} method.
*/
setValue(value: any[], options?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
/**
* Patches the value of the `FormArray`. It accepts an array that matches the
* structure of the control, and does its best to match the values to the correct
* controls in the group.
*
* It accepts both super-sets and sub-sets of the array without throwing an error.
*
* @usageNotes
* ### Patch the values for controls in a form array
*
* ```
* const arr = new FormArray([
* new FormControl(),
* new FormControl()
* ]);
* console.log(arr.value); // [null, null]
*
* arr.patchValue(['Nancy']);
* console.log(arr.value); // ['Nancy', null]
* ```
*
* @param value Array of latest values for the controls
* @param options Configure 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 value is updated.
* When false, no events are emitted.
* The configuration options are passed to the {@link AbstractControl#updateValueAndValidity
* updateValueAndValidity} method.
*/
patchValue(value: any[], options?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
/**
* Resets the `FormArray` and all descendants are marked `pristine` and `untouched`, and the
* value of all descendants to null or null maps.
*
* You reset to a specific form state by passing in an array of states
* that matches the structure of the control. The state is a standalone value
* or a form state object with both a value and a disabled status.
*
* @usageNotes
* ### Reset the values in a form array
*
* ```ts
* const arr = new FormArray([
* new FormControl(),
* new FormControl()
* ]);
* arr.reset(['name', 'last name']);
*
* console.log(this.arr.value); // ['name', 'last name']
* ```
*
* ### Reset the values in