@angular/forms
- Version 18.2.2
- Published
- 1.98 MB
- 1 dependency
- MIT license
Install
npm i @angular/forms
yarn add @angular/forms
pnpm add @angular/forms
Overview
Angular - directives and services for creating forms
Index
Variables
- CALL_SET_DISABLED_STATE
- CHECKBOX_REQUIRED_VALIDATOR
- COMPOSITION_BUFFER_MODE
- DEFAULT_VALUE_ACCESSOR
- EMAIL_VALIDATOR
- formArrayNameProvider
- FormControl
- MAX_LENGTH_VALIDATOR
- MAX_VALIDATOR
- MIN_LENGTH_VALIDATOR
- MIN_VALIDATOR
- modelGroupProvider
- NG_ASYNC_VALIDATORS
- NG_MODEL_WITH_FORM_CONTROL_WARNING
- NG_VALIDATORS
- NG_VALUE_ACCESSOR
- ngControlStatusHost
- ngGroupStatusHost
- PATTERN_VALIDATOR
- REACTIVE_DRIVEN_DIRECTIVES
- REQUIRED_VALIDATOR
- SHARED_FORM_DIRECTIVES
- TEMPLATE_DRIVEN_DIRECTIVES
- UntypedFormArray
- UntypedFormControl
- UntypedFormGroup
- VERSION
Functions
Classes
AbstractControl
- addAsyncValidators()
- addValidators()
- asyncValidator
- clearAsyncValidators()
- clearValidators()
- dirty
- disable()
- disabled
- enable()
- enabled
- errors
- events
- get()
- getError()
- getRawValue()
- hasAsyncValidator()
- hasError()
- hasValidator()
- invalid
- markAllAsTouched()
- markAsDirty()
- markAsPending()
- markAsPristine()
- markAsTouched()
- markAsUntouched()
- parent
- patchValue()
- pending
- pristine
- removeAsyncValidators()
- removeValidators()
- reset()
- root
- setAsyncValidators()
- setErrors()
- setParent()
- setValidators()
- setValue()
- status
- statusChanges
- touched
- untouched
- updateOn
- updateValueAndValidity()
- valid
- validator
- value
- valueChanges
Interfaces
Type Aliases
Namespaces
i10
- AsyncValidator
- AsyncValidatorFn
- CHECKBOX_REQUIRED_VALIDATOR
- CheckboxRequiredValidator
- EMAIL_VALIDATOR
- EmailValidator
- MAX_LENGTH_VALIDATOR
- MAX_VALIDATOR
- MaxLengthValidator
- MaxValidator
- MIN_LENGTH_VALIDATOR
- MIN_VALIDATOR
- MinLengthValidator
- MinValidator
- PATTERN_VALIDATOR
- PatternValidator
- REQUIRED_VALIDATOR
- RequiredValidator
- ValidationErrors
- Validator
- ValidatorFn
i4_2
- CALL_SET_DISABLED_STATE
- CheckboxControlValueAccessor
- ControlValueAccessor
- DefaultValueAccessor
- FormArrayName
- FormControlDirective
- FormControlName
- FormGroupDirective
- FormGroupName
- InternalFormsSharedModule
- NG_MODEL_WITH_FORM_CONTROL_WARNING
- NgControl
- NgControlStatus
- NgControlStatusGroup
- NgForm
- NgModel
- NgModelGroup
- NgSelectMultipleOption
- NgSelectOption
- NumberValueAccessor
- ɵInternalFormsSharedModule
- RadioControlValueAccessor
- RangeValueAccessor
- REACTIVE_DRIVEN_DIRECTIVES
- SelectControlValueAccessor
- SelectMultipleControlValueAccessor
- SHARED_FORM_DIRECTIVES
- TEMPLATE_DRIVEN_DIRECTIVES
Variables
variable CALL_SET_DISABLED_STATE
const CALL_SET_DISABLED_STATE: InjectionToken<SetDisabledStateOption>;
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 Also
variable CHECKBOX_REQUIRED_VALIDATOR
const CHECKBOX_REQUIRED_VALIDATOR: Provider;
Provider which adds
CheckboxRequiredValidator
to theNG_VALIDATORS
multi-provider list.
variable COMPOSITION_BUFFER_MODE
const COMPOSITION_BUFFER_MODE: InjectionToken<boolean>;
Provide this token to control if form directives buffer IME input until the "compositionend" event occurs.
variable DEFAULT_VALUE_ACCESSOR
const DEFAULT_VALUE_ACCESSOR: Provider;
variable EMAIL_VALIDATOR
const EMAIL_VALIDATOR: any;
Provider which adds
EmailValidator
to theNG_VALIDATORS
multi-provider list.
variable formArrayNameProvider
const formArrayNameProvider: any;
variable FormControl
const FormControl: ɵFormControlCtor;
variable MAX_LENGTH_VALIDATOR
const MAX_LENGTH_VALIDATOR: any;
Provider which adds
MaxLengthValidator
to theNG_VALIDATORS
multi-provider list.
variable MAX_VALIDATOR
const MAX_VALIDATOR: Provider;
Provider which adds
MaxValidator
to theNG_VALIDATORS
multi-provider list.
variable MIN_LENGTH_VALIDATOR
const MIN_LENGTH_VALIDATOR: any;
Provider which adds
MinLengthValidator
to theNG_VALIDATORS
multi-provider list.
variable MIN_VALIDATOR
const MIN_VALIDATOR: Provider;
Provider which adds
MinValidator
to theNG_VALIDATORS
multi-provider list.
variable modelGroupProvider
const modelGroupProvider: any;
variable NG_ASYNC_VALIDATORS
const NG_ASYNC_VALIDATORS: InjectionToken<readonly (Function | Validator)[]>;
An
InjectionToken
for registering additional asynchronous validators used withAbstractControl
s.See Also
### Provide a custom async validator directive
The following example implements the
AsyncValidator
interface to create an async validator directive with a custom error key.@Directive({selector: '[customAsyncValidator]',providers: [{provide: NG_ASYNC_VALIDATORS, useExisting: CustomAsyncValidatorDirective, multi:true}]})class CustomAsyncValidatorDirective implements AsyncValidator {validate(control: AbstractControl): Promise<ValidationErrors|null> {return Promise.resolve({'custom': true});}}
variable NG_MODEL_WITH_FORM_CONTROL_WARNING
const NG_MODEL_WITH_FORM_CONTROL_WARNING: InjectionToken<unknown>;
Token to provide to turn off the ngModel warning on formControl and formControlName.
variable NG_VALIDATORS
const NG_VALIDATORS: InjectionToken<readonly (Function | Validator)[]>;
An
InjectionToken
for registering additional synchronous validators used withAbstractControl
s.See Also
### Providing a custom validator
The following example registers a custom validator directive. Adding the validator to the existing collection of validators requires the
multi: true
option.@Directive({selector: '[customValidator]',providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}]})class CustomValidatorDirective implements Validator {validate(control: AbstractControl): ValidationErrors | null {return { 'custom': true };}}
variable NG_VALUE_ACCESSOR
const NG_VALUE_ACCESSOR: InjectionToken<readonly ControlValueAccessor[]>;
Used to provide a
ControlValueAccessor
for form controls.See
DefaultValueAccessor
for how to implement one.
variable ngControlStatusHost
const ngControlStatusHost: { '[class.ng-untouched]': string; '[class.ng-touched]': string; '[class.ng-pristine]': string; '[class.ng-dirty]': string; '[class.ng-valid]': string; '[class.ng-invalid]': string; '[class.ng-pending]': string;};
variable ngGroupStatusHost
const ngGroupStatusHost: { '[class.ng-submitted]': string; '[class.ng-untouched]': string; '[class.ng-touched]': string; '[class.ng-pristine]': string; '[class.ng-dirty]': string; '[class.ng-valid]': string; '[class.ng-invalid]': string; '[class.ng-pending]': string;};
variable PATTERN_VALIDATOR
const PATTERN_VALIDATOR: any;
Provider which adds
PatternValidator
to theNG_VALIDATORS
multi-provider list.
variable REACTIVE_DRIVEN_DIRECTIVES
const REACTIVE_DRIVEN_DIRECTIVES: Type<any>[];
variable REQUIRED_VALIDATOR
const REQUIRED_VALIDATOR: Provider;
Provider which adds
RequiredValidator
to theNG_VALIDATORS
multi-provider list.
variable SHARED_FORM_DIRECTIVES
const SHARED_FORM_DIRECTIVES: Type<any>[];
variable TEMPLATE_DRIVEN_DIRECTIVES
const TEMPLATE_DRIVEN_DIRECTIVES: Type<any>[];
variable UntypedFormArray
const UntypedFormArray: UntypedFormArrayCtor;
variable UntypedFormControl
const UntypedFormControl: UntypedFormControlCtor;
variable UntypedFormGroup
const UntypedFormGroup: UntypedFormGroupCtor;
variable VERSION
const VERSION: Version;
Functions
function isFormArray
isFormArray: (control: unknown) => control is FormArray<any>;
Asserts that the given control is an instance of
FormArray
function isFormControl
isFormControl: (control: unknown) => control is FormControl<any>;
Asserts that the given control is an instance of
FormControl
function isFormGroup
isFormGroup: (control: unknown) => control is FormGroup<any>;
Asserts that the given control is an instance of
FormGroup
function isFormRecord
isFormRecord: ( control: unknown) => control is FormRecord<AbstractControl<any, any>>;
Asserts that the given control is an instance of
FormRecord
Classes
class AbstractControl
abstract class AbstractControl<TValue = any, TRawValue extends TValue = TValue> {}
This is the base class for
FormControl
,FormGroup
, andFormArray
.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
, anddirty
. 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 Also
[Forms Guide](guide/forms)
[Reactive Forms Guide](guide/forms/reactive-forms)
[Dynamic Forms Guide](guide/forms/dynamic-forms)
constructor
constructor( validators: ValidatorFn | ValidatorFn[], asyncValidators: AsyncValidatorFn | AsyncValidatorFn[]);
Initialize the AbstractControl instance.
Parameter validators
The function or array of functions that is used to determine the validity of this control synchronously.
Parameter asyncValidators
The function or array of functions that is used to determine validity of this control asynchronously.
property asyncValidator
asyncValidator: AsyncValidatorFn;
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.
property dirty
readonly dirty: 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.
property disabled
readonly disabled: boolean;
A control is
disabled
when itsstatus
isDISABLED
.Disabled controls are exempt from validation checks and are not included in the aggregate value of their ancestor controls.
Returns
True if the control is disabled, false otherwise.
See Also
property enabled
readonly enabled: boolean;
A control is
enabled
as long as itsstatus
is notDISABLED
.Returns
True if the control has any status other than 'DISABLED', false if the status is 'DISABLED'.
See Also
property errors
readonly errors: ValidationErrors;
An object containing any errors generated by failing validation, or null if there are no errors.
property events
readonly events: Observable<ControlEvent<TValue>>;
A 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 theevents
of the parent control instead. For other event types, the events are emitted after the parent control has been updated.
property invalid
readonly invalid: boolean;
A control is
invalid
when itsstatus
isINVALID
.Returns
True if this control has failed one or more of its validation checks, false otherwise.
See Also
property parent
readonly parent: FormGroup<any> | FormArray<any>;
The parent control.
property pending
readonly pending: boolean;
A control is
pending
when itsstatus
isPENDING
.Returns
True if this control is in the process of conducting a validation check, false otherwise.
See Also
property pristine
pristine: boolean;
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.
property root
readonly root: AbstractControl<any, any>;
Retrieves the top-level ancestor of this control.
property status
status: FormControlStatus;
The validation status of the control.
See Also
These status values are mutually exclusive, so a control cannot be both valid AND invalid or invalid AND disabled.
property statusChanges
readonly statusChanges: Observable<FormControlStatus>;
A multicasting observable that emits an event every time the validation
status
of the control recalculates.See Also
TODO: this should be piped from events() but is breaking in G3
property touched
touched: boolean;
True if the control is marked as
touched
.A control is marked
touched
once the user has triggered ablur
event on it.
property untouched
readonly untouched: boolean;
True if the control has not been marked as touched
A control is
untouched
if the user has not yet triggered ablur
event on it.
property updateOn
readonly updateOn: FormHooks;
Reports the update strategy of the
AbstractControl
(meaning the event on which the control updates itself). Possible values:'change'
|'blur'
|'submit'
Default value:'change'
property valid
readonly valid: boolean;
A control is
valid
when itsstatus
isVALID
.Returns
True if the control has passed all of its validation tests, false otherwise.
See Also
property validator
validator: ValidatorFn;
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.
property value
readonly value: {};
The current value of the control.
* For a
FormControl
, the current value. * For an enabledFormGroup
, the values of enabled controls as an object with a key-value pair for each member of the group. * For a disabledFormGroup
, the values of all controls as an object with a key-value pair for each member of the group. * For aFormArray
, the values of enabled controls as an array.
property valueChanges
readonly 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 thevalueChanges
event of the parent control instead.TODO: this should be piped from events() but is breaking in G3
method addAsyncValidators
addAsyncValidators: (validators: AsyncValidatorFn | AsyncValidatorFn[]) => 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.
Parameter validators
The new asynchronous validator function or functions to add to this control.
method addValidators
addValidators: (validators: ValidatorFn | ValidatorFn[]) => 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.Parameter validators
The new validator function or functions to add to this control.
method clearAsyncValidators
clearAsyncValidators: () => 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.
method clearValidators
clearValidators: () => void;
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.
method disable
disable: (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.
Parameter 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), thestatusChanges
,valueChanges
andevents
observables emit events with the latest status and value when the control is disabled. When false, no events are emitted.See Also
method enable
enable: (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.
Parameter 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), thestatusChanges
,valueChanges
andevents
observables emit events with the latest status and value when the control is enabled. When false, no events are emitted.See Also
method get
get: { <P extends string | readonly (string | number)[]>(path: P): AbstractControl< ɵGetProperty<TRawValue, P> > | null; <P extends string | (string | number)[]>(path: P): AbstractControl< ɵGetProperty<TRawValue, P>, ɵGetProperty<TRawValue, P> >;};
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)
).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 areadonly
array if possible.
method getError
getError: (errorCode: string, path?: Array<string | number> | string) => any;
Reports error data for the control with the given path.
Parameter errorCode
The code of the error to check
Parameter path
A list of control names that designates how to move from the current control to the control that should be queried for errors.
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.
method getRawValue
getRawValue: () => any;
The raw value of this control. For most control implementations, the raw value will include disabled children.
method hasAsyncValidator
hasAsyncValidator: (validator: AsyncValidatorFn) => 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.
Parameter validator
The asynchronous validator to check for presence. Compared by function reference.
Returns
Whether the provided asynchronous validator was found on this control.
method hasError
hasError: (errorCode: string, path?: Array<string | number> | string) => boolean;
Reports whether the control with the given path has the error specified.
Parameter errorCode
The code of the error to check
Parameter path
A list of control names that designates how to move from the current control to the control that should be queried for errors.
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.
method hasValidator
hasValidator: (validator: ValidatorFn) => boolean;
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.
### Reference 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)Parameter validator
The validator to check for presence. Compared by function reference.
Returns
Whether the provided validator was found on this control.
method markAllAsTouched
markAllAsTouched: (opts?: { emitEvent?: boolean }) => void;
Marks the control and all its descendant controls as
touched
.Parameter opts
Configuration options that determine how the control propagates changes and emits events after marking is applied. *
emitEvent
: When true or not supplied (the default), theevents
observable emits aTouchedChangeEvent
with thetouched
property beingtrue
. When false, no events are emitted.See Also
method markAsDirty
markAsDirty: (opts?: { onlySelf?: boolean; emitEvent?: boolean }) => void;
Marks the control as
dirty
. A control becomes dirty when the control's value is changed through the UI; comparemarkAsTouched
.Parameter 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), theevents
observable emits aPristineChangeEvent
with thepristine
property beingfalse
. When false, no events are emitted.See Also
method markAsPending
markAsPending: (opts?: { onlySelf?: boolean; emitEvent?: boolean }) => void;
Marks the control as
pending
.A control is pending while the control performs async validation.
Parameter 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), thestatusChanges
observable emits an event with the latest status the control is marked pending and theevents
observable emits aStatusChangeEvent
with thestatus
property beingPENDING
When false, no events are emitted.See Also
method markAsPristine
markAsPristine: (opts?: { onlySelf?: boolean; emitEvent?: boolean }) => void;
Marks the control as
pristine
.If the control has any children, marks all children as
pristine
, and recalculates thepristine
status of all parent controls.Parameter 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. *emitEvent
: When true or not supplied (the default), theevents
observable emits aPristineChangeEvent
with thepristine
property beingtrue
. When false, no events are emitted.See Also
method markAsTouched
markAsTouched: (opts?: { onlySelf?: boolean; emitEvent?: boolean }) => void;
Marks the control as
touched
. A control is touched by focus and blur events that do not change the value.Parameter 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), theevents
observable emits aTouchedChangeEvent
with thetouched
property beingtrue
. When false, no events are emitted.See Also
method markAsUntouched
markAsUntouched: (opts?: { onlySelf?: boolean; emitEvent?: boolean }) => void;
Marks the control as
untouched
.If the control has any children, also marks all children as
untouched
and recalculates thetouched
status of all parent controls.Parameter 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. *emitEvent
: When true or not supplied (the default), theevents
observable emits aTouchedChangeEvent
with thetouched
property beingfalse
. When false, no events are emitted.See Also
method patchValue
abstract patchValue: (value: TValue, options?: Object) => void;
Patches the value of the control. Abstract method (implemented in sub-classes).
method removeAsyncValidators
removeAsyncValidators: ( validators: AsyncValidatorFn | AsyncValidatorFn[]) => 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.Parameter validators
The asynchronous validator or validators to remove.
method removeValidators
removeValidators: (validators: ValidatorFn | ValidatorFn[]) => 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.
### Reference 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.Parameter validators
The validator or validators to remove.
method reset
abstract reset: (value?: TValue, options?: Object) => void;
Resets the control. Abstract method (implemented in sub-classes).
method setAsyncValidators
setAsyncValidators: ( validators: AsyncValidatorFn | AsyncValidatorFn[] | 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.
method setErrors
setErrors: ( errors: ValidationErrors | null, opts?: { emitEvent?: boolean }) => void;
Sets errors on a form control when running validations manually, rather than automatically.
Calling
setErrors
also updates the validity of the parent control.Parameter 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), thestatusChanges
observable emits an event after the errors are set.### 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);
method setParent
setParent: (parent: FormGroup | FormArray | null) => void;
Sets the parent of the control
Parameter parent
The new parent.
method setValidators
setValidators: (validators: ValidatorFn | ValidatorFn[] | null) => void;
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.
method setValue
abstract setValue: (value: TRawValue, options?: Object) => void;
Sets the value of the control. Abstract method (implemented in sub-classes).
method updateValueAndValidity
updateValueAndValidity: (opts?: { onlySelf?: boolean; emitEvent?: boolean;}) => void;
Recalculates the value and validation status of the control.
By default, it also updates the value and validity of its ancestors.
Parameter 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), thestatusChanges
,valueChanges
andevents
observables emit events with the latest status and value when the control is updated. When false, no events are emitted.
class AbstractControlDirective
abstract class AbstractControlDirective {}
Base class for control directives.
This class is only used internally in the
ReactiveFormsModule
and theFormsModule
.
property asyncValidator
readonly asyncValidator: AsyncValidatorFn;
Asynchronous validator function composed of all the asynchronous validators registered with this directive.
property control
readonly control: AbstractControl<any, any>;
A reference to the underlying control.
Returns
the control that backs this directive. Most properties fall through to that instance.
property dirty
readonly dirty: boolean;
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.
property disabled
readonly disabled: boolean;
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.
property enabled
readonly enabled: boolean;
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.
property errors
readonly errors: ValidationErrors;
Reports the control's validation errors. If the control is not present, null is returned.
property invalid
readonly invalid: boolean;
Reports whether the control is invalid, meaning that an error exists in the input value. If the control is not present, null is returned.
property path
readonly path: string[];
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.
property pending
readonly pending: boolean;
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.
property pristine
readonly pristine: boolean;
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.
property status
readonly status: string;
Reports the validation status of the control. Possible values include: 'VALID', 'INVALID', 'DISABLED', and 'PENDING'. If the control is not present, null is returned.
property statusChanges
readonly statusChanges: any;
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.
property touched
readonly touched: boolean;
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.
property untouched
readonly untouched: boolean;
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.
property valid
readonly valid: boolean;
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.
property validator
readonly validator: ValidatorFn;
Synchronous validator function composed of all the synchronous validators registered with this directive.
property value
readonly value: any;
Reports the value of the control if it is present, otherwise null.
property valueChanges
readonly valueChanges: any;
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.
method getError
getError: (errorCode: string, path?: Array<string | number> | string) => any;
Reports error data for the control with the given path.
Parameter errorCode
The code of the error to check
Parameter path
A list of control names that designates how to move from the current control to the control that should be queried for errors.
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.
method hasError
hasError: (errorCode: string, path?: Array<string | number> | string) => boolean;
Reports whether the control with the given path has the error specified.
Parameter errorCode
The code of the error to check
Parameter path
A list of control names that designates how to move from the current control to the control that should be queried for errors.
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.
method reset
reset: (value?: any) => void;
Resets the control with the provided value if the control is present.
class AbstractFormGroupDirective
class AbstractFormGroupDirective extends ControlContainer implements OnInit, OnDestroy {}
A base class for code shared between the
NgModelGroup
andFormGroupName
directives.
property control
readonly control: FormGroup<any>;
The
FormGroup
bound to this directive.
property formDirective
readonly formDirective: Form;
The top-level directive for this group if present, otherwise null.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< AbstractFormGroupDirective, never, never, {}, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<AbstractFormGroupDirective, never>;
property path
readonly path: string[];
The path to this group from the top-level directive.
method ngOnDestroy
ngOnDestroy: () => void;
method ngOnInit
ngOnInit: () => void;
class CheckboxControlValueAccessor
class CheckboxControlValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor {}
A
ControlValueAccessor
for writing a value and listening to changes on a checkbox input element.### Using a checkbox with a reactive form.
The following example shows how to use a checkbox with a reactive form.
const rememberLoginControl = new FormControl();<input type="checkbox" [formControl]="rememberLoginControl">ReactiveFormsModule FormsModule
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< CheckboxControlValueAccessor, 'input[type=checkbox][formControlName],input[type=checkbox][formControl],input[type=checkbox][ngModel]', never, {}, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<CheckboxControlValueAccessor, never>;
method writeValue
writeValue: (value: any) => void;
Sets the "checked" property on the input element.
class CheckboxRequiredValidator
class CheckboxRequiredValidator extends RequiredValidator {}
A Directive that adds the
required
validator to checkbox controls marked with therequired
attribute. The directive is provided with theNG_VALIDATORS
multi-provider list.See Also
[Form Validation](guide/forms/form-validation)
### 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>FormsModule ReactiveFormsModule
property ɵdir
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>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<CheckboxRequiredValidator, never>;
class ControlContainer
abstract class ControlContainer extends AbstractControlDirective {}
A base class for directives that contain multiple registered instances of
NgControl
. Only used by the forms module.
property formDirective
readonly formDirective: Form;
The top-level form directive for the control.
property name
name: string | number;
The name for the control
property path
readonly path: string[];
The path to this group.
class ControlEvent
abstract class ControlEvent<T = any> {}
Base class for every event sent by
AbstractControl.events()
property source
abstract readonly source: AbstractControl<unknown, unknown>;
Form control from which this event is originated.
class DefaultValueAccessor
class DefaultValueAccessor extends BaseControlValueAccessor implements ControlValueAccessor {}
The default
ControlValueAccessor
for writing a value and listening to changes on input elements. The accessor is used by theFormControlDirective
,FormControlName
, andNgModel
directives.### 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).
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 thengDefaultControl
attribute as shown below.<custom-input-component ngDefaultControl [(ngModel)]="value"></custom-input-component>ReactiveFormsModule FormsModule
constructor
constructor( renderer: Renderer2, elementRef: ElementRef, _compositionMode: boolean);
property ɵdir
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>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< DefaultValueAccessor, [null, null, { optional: true }]>;
method writeValue
writeValue: (value: any) => void;
Sets the "value" property on the input element.
class EmailValidator
class EmailValidator extends AbstractValidatorDirective {}
A directive that adds the
email
validator to controls marked with theemail
attribute. The directive is provided with theNG_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 on the [Validators.email page](api/forms/Validators#email).
See Also
[Form Validation](guide/forms/form-validation)
### 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">FormsModule ReactiveFormsModule
property email
email: string | boolean;
Tracks changes to the email attribute bound to this directive.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< EmailValidator, '[email][formControlName],[email][formControl],[email][ngModel]', never, { email: { alias: 'email'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<EmailValidator, never>;
method enabled
enabled: (input: boolean) => boolean;
class FormArray
class FormArray<TControl extends AbstractControl<any> = any> extends AbstractControl< ɵTypedOrUntyped<TControl, ɵFormArrayValue<TControl>, any>, ɵTypedOrUntyped<TControl, ɵFormArrayRawValue<TControl>, any>> {}
Tracks the value and validity state of an array of
FormControl
,FormGroup
orFormArray
instances.A
FormArray
aggregates the values of each childFormControl
into an array. It calculates its status by reducing the status values of its children. For example, if one of the controls in aFormArray
is invalid, the entire array becomes invalid.FormArray
accepts one generic argument, which is the type of the controls inside. If you need a heterogenous array, use UntypedFormArray.FormArray
is one of the four fundamental building blocks used to define forms in Angular, along withFormControl
,FormGroup
, andFormRecord
.### 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 setupdateOn
to'blur'
at the array level, all child controls default to 'blur', unless the child has explicitly specified a differentupdateOn
value.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
orclear
methods inFormArray
itself. These methods ensure the controls are properly tracked in the form's hierarchy. Do not modify the array ofAbstractControl
s used to instantiate theFormArray
directly, as that result in strange and unexpected behavior such as broken change detection.
constructor
constructor( controls: TControl[], validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]);
Creates a new
FormArray
instance.Parameter controls
An array of child controls. Each child control is given an index where it is registered.
Parameter validatorOrOpts
A synchronous validator function, or an array of such functions, or an
AbstractControlOptions
object that contains validation functions and a validation trigger.Parameter asyncValidator
A single async validator or array of async validator functions
property controls
controls: TControl[] | AbstractControl<any, any>[];
property length
readonly length: number;
Length of the control array.
method at
at: (index: number) => ɵTypedOrUntyped<TControl, TControl, AbstractControl<any>>;
Get the
AbstractControl
at the givenindex
in the array.Parameter index
Index in the array to retrieve the control. If
index
is negative, it will wrap around from the back, and if index is greatly negative (less than-length
), the result is undefined. This behavior is the same asArray.at(index)
.
method clear
clear: (options?: { emitEvent?: boolean }) => void;
Remove all controls in the
FormArray
.Parameter options
Specifies whether this FormArray instance should emit events after all controls are removed. *
emitEvent
: When true or not supplied (the default), both thestatusChanges
andvalueChanges
observables emit events with the latest status and value when all controls in this FormArray instance are removed. When false, no events are emitted.### Remove all elements from a FormArray
const arr = new FormArray([new FormControl(),new FormControl()]);console.log(arr.length); // 2arr.clear();console.log(arr.length); // 0It's a simpler and more efficient alternative to removing all elements one by one:
const arr = new FormArray([new FormControl(),new FormControl()]);while (arr.length) {arr.removeAt(0);}
method getRawValue
getRawValue: () => ɵFormArrayRawValue<TControl>;
The aggregate value of the array, including any disabled controls.
Reports all values regardless of disabled status.
method insert
insert: ( index: number, control: TControl, options?: { emitEvent?: boolean }) => void;
Insert a new
AbstractControl
at the givenindex
in the array.Parameter index
Index in the array to insert the control. If
index
is negative, wraps around from the back. Ifindex
is greatly negative (less than-length
), prepends to the array. This behavior is the same asArray.splice(index, 0, control)
.Parameter control
Form control to be inserted
Parameter options
Specifies whether this FormArray instance should emit events after a new control is inserted. *
emitEvent
: When true or not supplied (the default), both thestatusChanges
andvalueChanges
observables emit events with the latest status and value when the control is inserted. When false, no events are emitted.
method patchValue
patchValue: ( value: ɵFormArrayValue<TControl>, 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.
### 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]Parameter value
Array of latest values for the controls
Parameter 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 thestatusChanges
andvalueChanges
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 method.
method push
push: (control: TControl, options?: { emitEvent?: boolean }) => void;
Insert a new
AbstractControl
at the end of the array.Parameter control
Form control to be inserted
Parameter options
Specifies whether this FormArray instance should emit events after a new control is added. *
emitEvent
: When true or not supplied (the default), both thestatusChanges
andvalueChanges
observables emit events with the latest status and value when the control is inserted. When false, no events are emitted.
method removeAt
removeAt: (index: number, options?: { emitEvent?: boolean }) => void;
Remove the control at the given
index
in the array.Parameter index
Index in the array to remove the control. If
index
is negative, wraps around from the back. Ifindex
is greatly negative (less than-length
), removes the first element. This behavior is the same asArray.splice(index, 1)
.Parameter options
Specifies whether this FormArray instance should emit events after a control is removed. *
emitEvent
: When true or not supplied (the default), both thestatusChanges
andvalueChanges
observables emit events with the latest status and value when the control is removed. When false, no events are emitted.
method reset
reset: ( value?: ɵTypedOrUntyped<TControl, ɵFormArrayValue<TControl>, any>, options?: { onlySelf?: boolean; emitEvent?: boolean }) => void;
Resets the
FormArray
and all descendants are markedpristine
anduntouched
, 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.
### Reset the values in a form array
const arr = new FormArray([new FormControl(),new FormControl()]);arr.reset(['name', 'last name']);console.log(arr.value); // ['name', 'last name']### Reset the values in a form array and the disabled status for the first control
arr.reset([{value: 'name', disabled: true},'last']);console.log(arr.value); // ['last']console.log(arr.at(0).status); // 'DISABLED'Parameter value
Array of values for the controls
Parameter 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 thestatusChanges
andvalueChanges
observables emit events with the latest status and value when the control is reset. When false, no events are emitted. The configuration options are passed to the method.
method setControl
setControl: ( index: number, control: TControl, options?: { emitEvent?: boolean }) => void;
Replace an existing control.
Parameter index
Index in the array to replace the control. If
index
is negative, wraps around from the back. Ifindex
is greatly negative (less than-length
), replaces the first element. This behavior is the same asArray.splice(index, 1, control)
.Parameter control
The
AbstractControl
control to replace the existing controlParameter options
Specifies whether this FormArray instance should emit events after an existing control is replaced with a new one. *
emitEvent
: When true or not supplied (the default), both thestatusChanges
andvalueChanges
observables emit events with the latest status and value when the control is replaced with a new one. When false, no events are emitted.
method setValue
setValue: ( value: ɵFormArrayRawValue<TControl>, options?: { onlySelf?: boolean; emitEvent?: boolean }) => void;
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.
### 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']Parameter value
Array of values for the controls
Parameter 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 thestatusChanges
andvalueChanges
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 method.
class FormArrayName
class FormArrayName extends ControlContainer implements OnInit, OnDestroy {}
Syncs a nested
FormArray
to a DOM element.This directive is designed to be used with a parent
FormGroupDirective
(selector:[formGroup]
).It accepts the string name of the nested
FormArray
you want to link, and will look for aFormArray
registered with that name in the parentFormGroup
instance you passed intoFormGroupDirective
.See Also
[Reactive Forms Guide](guide/forms/reactive-forms)
### Example
ReactiveFormsModule
constructor
constructor( parent: ControlContainer, validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[]);
property control
readonly control: FormArray<any>;
The
FormArray
bound to this directive.
property formDirective
readonly formDirective: FormGroupDirective;
The top-level directive for this group if present, otherwise null.
property name
name: string | number;
Tracks the name of the
FormArray
bound to the directive. The name corresponds to a key in the parentFormGroup
orFormArray
. Accepts a name as a string or a number. The name in the form of a string is useful for individual forms, while the numerical form allows for form arrays to be bound to indices when iterating over arrays in aFormArray
.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< FormArrayName, '[formArrayName]', never, { name: { alias: 'formArrayName'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< FormArrayName, [ { optional: true; host: true; skipSelf: true }, { optional: true; self: true }, { optional: true; self: true } ]>;
property path
readonly path: string[];
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.
method ngOnDestroy
ngOnDestroy: () => void;
A lifecycle method called before the directive's instance is destroyed. For internal use only.
method ngOnInit
ngOnInit: () => void;
A lifecycle method called when the directive's inputs are initialized. For internal use only.
Throws
If the directive does not have a valid parent.
class FormBuilder
class FormBuilder {}
Creates an
AbstractControl
from a user-specified configuration.The
FormBuilder
provides syntactic sugar that shortens creating instances of aFormControl
,FormGroup
, orFormArray
. It reduces the amount of boilerplate needed to build complex forms.See Also
[Reactive Forms Guide](guide/forms/reactive-forms)
property nonNullable
readonly nonNullable: NonNullableFormBuilder;
Returns a FormBuilder in which automatically constructed
FormControl
elements have{nonNullable: true}
and are non-nullable.**Constructing non-nullable controls**
When constructing a control, it will be non-nullable, and will reset to its initial value.
let nnfb = new FormBuilder().nonNullable;let name = nnfb.control('Alex'); // FormControl<string>name.reset();console.log(name); // 'Alex'**Constructing non-nullable groups or arrays**
When constructing a group or array, all automatically created inner controls will be non-nullable, and will reset to their initial values.
let nnfb = new FormBuilder().nonNullable;let name = nnfb.group({who: 'Alex'}); // FormGroup<{who: FormControl<string>}>name.reset();console.log(name); // {who: 'Alex'}**Constructing *nullable* fields on groups or arrays**
It is still possible to have a nullable field. In particular, any
FormControl
which is *already* constructed will not be altered. For example:let nnfb = new FormBuilder().nonNullable;// FormGroup<{who: FormControl<string|null>}>let name = nnfb.group({who: new FormControl('Alex')});name.reset(); console.log(name); // {who: null}Because the inner control is constructed explicitly by the caller, the builder has no control over how it is created, and cannot exclude the
null
.
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<FormBuilder, never>;
property ɵprov
static ɵprov: i0.ɵɵInjectableDeclaration<FormBuilder>;
method array
array: <T>( controls: Array<T>, validatorOrOpts?: | ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null) => FormArray<ɵElement<T, null>>;
Constructs a new
FormArray
from the given array of configurations, validators and options. Accepts a single generic argument, which is the type of each control inside the array.Parameter controls
An array of child controls or control configs. Each child control is given an index when it is registered.
Parameter validatorOrOpts
A synchronous validator function, or an array of such functions, or an
AbstractControlOptions
object that contains validation functions and a validation trigger.Parameter asyncValidator
A single async validator or array of async validator functions.
method control
control: { <T>( formState: T | FormControlState<T>, opts: FormControlOptions & { initialValueIsDefault: true } ): FormControl<T>; <T>( formState: T | FormControlState<T>, opts: FormControlOptions & { nonNullable: true } ): FormControl<T>; <T>( formState: T | FormControlState<T>, opts: FormControlOptions, asyncValidator: AsyncValidatorFn | AsyncValidatorFn[] ): FormControl<T>; <T>( formState: T | FormControlState<T>, validatorOrOpts?: ValidatorFn | ValidatorFn[] | FormControlOptions, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] ): FormControl<T>;};
Deprecated
Use
nonNullable
instead.Deprecated
When passing an
options
argument, theasyncValidator
argument has no effect.
method group
group: { <T extends {}>( controls: T, options?: AbstractControlOptions | null ): FormGroup<{ [K in keyof T]: ɵElement<T[K], null> }>; ( controls: { [key: string]: any }, options: { [key: string]: any } ): FormGroup<any>;};
Constructs a new
FormGroup
instance. Accepts a single generic argument, which is an object containing all the keys and corresponding inner control types.Parameter controls
A collection of child controls. The key for each child is the name under which it is registered.
Parameter options
Configuration options object for the
FormGroup
. The object should have theAbstractControlOptions
type and might contain the following fields: *validators
: A synchronous validator function, or an array of validator functions. *asyncValidators
: A single async validator or array of async validator functions. *updateOn
: The event upon which the control should be updated (options: 'change' | 'blur' | submit').Constructs a new
FormGroup
instance.Parameter controls
A record of child controls. The key for each child is the name under which the control is registered.
Parameter options
Configuration options object for the
FormGroup
. The legacy configuration object consists of: *validator
: A synchronous validator function, or an array of validator functions. *asyncValidator
: A single async validator or array of async validator functions Note: the legacy format is deprecated and might be removed in one of the next major versions of Angular.Deprecated
This API is not typesafe and can result in issues with Closure Compiler renaming. Use the
FormBuilder#group
overload withAbstractControlOptions
instead. Note thatAbstractControlOptions
expectsvalidators
andasyncValidators
to be valid validators. If you have custom validators, make sure their validation function parameter isAbstractControl
and not a sub-class, such asFormGroup
. These functions will be called with an object of typeAbstractControl
and that cannot be automatically downcast to a subclass, so TypeScript sees this as an error. For example, change the `(group: FormGroup) => ValidationErrors|nullsignature to be
(group: AbstractControl) => ValidationErrors|null`.
method record
record: <T>( controls: { [key: string]: T }, options?: AbstractControlOptions | null) => FormRecord<ɵElement<T, null>>;
Constructs a new
FormRecord
instance. Accepts a single generic argument, which is an object containing all the keys and corresponding inner control types.Parameter controls
A collection of child controls. The key for each child is the name under which it is registered.
Parameter options
Configuration options object for the
FormRecord
. The object should have theAbstractControlOptions
type and might contain the following fields: *validators
: A synchronous validator function, or an array of validator functions. *asyncValidators
: A single async validator or array of async validator functions. *updateOn
: The event upon which the control should be updated (options: 'change' | 'blur' | submit').
class FormControlDirective
class FormControlDirective extends NgControl implements OnChanges, OnDestroy {}
Synchronizes a standalone
FormControl
instance to a form control element.Note that support for using the
ngModel
input property andngModelChange
event with reactive form directives was deprecated in Angular v6 and is scheduled for removal in a future version of Angular.See Also
[Reactive Forms Guide](guide/forms/reactive-forms)
The following example shows how to register a standalone control and set its value.
ReactiveFormsModule
constructor
constructor( validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[], valueAccessors: ControlValueAccessor[], _ngModelWarningConfig: string, callSetDisabledState?: SetDisabledStateOption);
property control
readonly control: FormControl<any>;
The
FormControl
bound to this directive.
property form
form: FormControl<any>;
Tracks the
FormControl
instance bound to the directive.
property model
model: any;
Deprecated
as of v6
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< FormControlDirective, '[formControl]', ['ngForm'], { form: { alias: 'formControl'; required: false }; isDisabled: { alias: 'disabled'; required: false }; model: { alias: 'ngModel'; required: false }; }, { update: 'ngModelChange' }, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< FormControlDirective, [ { optional: true; self: true }, { optional: true; self: true }, { optional: true; self: true }, { optional: true }, { optional: true } ]>;
property path
readonly path: string[];
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.
property update
update: EventEmitter<any>;
Deprecated
as of v6
property viewModel
viewModel: any;
Internal reference to the view model value.
method ngOnChanges
ngOnChanges: (changes: SimpleChanges) => void;
method ngOnDestroy
ngOnDestroy: () => void;
method viewToModelUpdate
viewToModelUpdate: (newValue: any) => void;
Sets the new value for the view model and emits an
ngModelChange
event.Parameter newValue
The new value for the view model.
class FormControlName
class FormControlName extends NgControl implements OnChanges, OnDestroy {}
Syncs a
FormControl
in an existingFormGroup
to a form control element by name.See Also
[Reactive Forms Guide](guide/forms/reactive-forms)
### Register
FormControl
within a groupThe following example shows how to register multiple form controls within a form group and set their value.
To see
formControlName
examples with different form control types, see:* Radio buttons:
RadioControlValueAccessor
* Selects:SelectControlValueAccessor
### Use with ngModel is deprecated
Support for using the
ngModel
input property andngModelChange
event with reactive form directives has been deprecated in Angular v6 and is scheduled for removal in a future version of Angular.ReactiveFormsModule
constructor
constructor( parent: ControlContainer, validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[], valueAccessors: ControlValueAccessor[], _ngModelWarningConfig: string);
property control
readonly control: FormControl<any>;
Tracks the
FormControl
instance bound to the directive.
property formDirective
readonly formDirective: any;
The top-level directive for this group if present, otherwise null.
property model
model: any;
Deprecated
as of v6
property name
name: string | number;
Tracks the name of the
FormControl
bound to the directive. The name corresponds to a key in the parentFormGroup
orFormArray
. Accepts a name as a string or a number. The name in the form of a string is useful for individual forms, while the numerical form allows for form controls to be bound to indices when iterating over controls in aFormArray
.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< FormControlName, '[formControlName]', never, { name: { alias: 'formControlName'; required: false }; isDisabled: { alias: 'disabled'; required: false }; model: { alias: 'ngModel'; required: false }; }, { update: 'ngModelChange' }, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< FormControlName, [ { optional: true; host: true; skipSelf: true }, { optional: true; self: true }, { optional: true; self: true }, { optional: true; self: true }, { optional: true } ]>;
property path
readonly path: string[];
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.
property update
update: EventEmitter<any>;
Deprecated
as of v6
method ngOnChanges
ngOnChanges: (changes: SimpleChanges) => void;
method ngOnDestroy
ngOnDestroy: () => void;
method viewToModelUpdate
viewToModelUpdate: (newValue: any) => void;
Sets the new value for the view model and emits an
ngModelChange
event.Parameter newValue
The new value for the view model.
class FormGroup
class FormGroup< TControl extends { [K in keyof TControl]: AbstractControl<any>; } = any> extends AbstractControl< ɵTypedOrUntyped<TControl, ɵFormGroupValue<TControl>, any>, ɵTypedOrUntyped<TControl, ɵFormGroupRawValue<TControl>, any>> {}
Tracks the value and validity state of a group of
FormControl
instances.A
FormGroup
aggregates the values of each childFormControl
into one object, with each control name as the key. It calculates its status by reducing the status values of its children. For example, if one of the controls in a group is invalid, the entire group becomes invalid.FormGroup
is one of the four fundamental building blocks used to define forms in Angular, along withFormControl
,FormArray
, andFormRecord
.When instantiating a
FormGroup
, pass in a collection of child controls as the first argument. The key for each child registers the name for the control.FormGroup
is intended for use cases where the keys are known ahead of time. If you need to dynamically add and remove controls, use FormRecord instead.FormGroup
accepts an optional type parameterTControl
, which is an object type with inner control types as values.### Create a form group with 2 controls
const form = new FormGroup({first: new FormControl('Nancy', Validators.minLength(2)),last: new FormControl('Drew'),});console.log(form.value); // {first: 'Nancy', last; 'Drew'}console.log(form.status); // 'VALID'### The type argument, and optional controls
FormGroup
accepts one generic argument, which is an object containing its inner controls. This type will usually be inferred automatically, but you can always specify it explicitly if you wish.If you have controls that are optional (i.e. they can be removed, you can use the
?
in the type):const form = new FormGroup<{first: FormControl<string|null>,middle?: FormControl<string|null>, // Middle name is optional.last: FormControl<string|null>,}>({first: new FormControl('Nancy'),last: new FormControl('Drew'),});### Create a form group with a group-level validator
You include group-level validators as the second arg, or group-level async validators as the third arg. These come in handy when you want to perform validation that considers the value of more than one child control.
const form = new FormGroup({password: new FormControl('', Validators.minLength(2)),passwordConfirm: new FormControl('', Validators.minLength(2)),}, passwordMatchValidator);function passwordMatchValidator(g: FormGroup) {return g.get('password').value === g.get('passwordConfirm').value? null : {'mismatch': true};}Like
FormControl
instances, you choose to pass in validators and async validators as part of an options object.const form = new FormGroup({password: new FormControl('')passwordConfirm: new FormControl('')}, { validators: passwordMatchValidator, asyncValidators: otherValidator });### Set the updateOn property for all controls in a form group
The options object is used to set a default value for each child control's
updateOn
property. If you setupdateOn
to'blur'
at the group level, all child controls default to 'blur', unless the child has explicitly specified a differentupdateOn
value.const c = new FormGroup({one: new FormControl()}, { updateOn: 'blur' });### Using a FormGroup with optional controls
It is possible to have optional controls in a FormGroup. An optional control can be removed later using
removeControl
, and can be omitted when callingreset
. Optional controls must be declared optional in the group's type.const c = new FormGroup<{one?: FormControl<string>}>({one: new FormControl('')});Notice that
c.value.one
has typestring|null|undefined
. This is because callingc.reset({})
without providing the optional keyone
will cause it to becomenull
.
constructor
constructor( controls: { [K in keyof TControl]: AbstractControl<any, any> }, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]);
Creates a new
FormGroup
instance.Parameter controls
A collection of child controls. The key for each child is the name under which it is registered.
Parameter validatorOrOpts
A synchronous validator function, or an array of such functions, or an
AbstractControlOptions
object that contains validation functions and a validation trigger.Parameter asyncValidator
A single async validator or array of async validator functions
property controls
controls: | { [K in keyof TControl]: AbstractControl<any, any> } | { [key: string]: AbstractControl<any, any> };
method addControl
addControl: { ( this: FormGroup<{ [key: string]: AbstractControl<any, any> }>, name: string, control: AbstractControl, options?: { emitEvent?: boolean } ): void; <K extends string & keyof TControl>( name: K, control: Required<TControl>[K], options?: { emitEvent?: boolean } ): void;};
Add a control to this group. In a strongly-typed group, the control must be in the group's type (possibly as an optional key).
If a control with a given name already exists, it would *not* be replaced with a new one. If you want to replace an existing control, use the method instead. This method also updates the value and validity of the control.
Parameter name
The control name to add to the collection
Parameter control
Provides the control for the given name
Parameter options
Specifies whether this FormGroup instance should emit events after a new control is added. *
emitEvent
: When true or not supplied (the default), both thestatusChanges
andvalueChanges
observables emit events with the latest status and value when the control is added. When false, no events are emitted.
method contains
contains: { <K extends string>(controlName: K): boolean; ( this: FormGroup<{ [key: string]: AbstractControl<any, any> }>, controlName: string ): boolean;};
Check whether there is an enabled control with the given name in the group.
Reports false for disabled controls. If you'd like to check for existence in the group only, use instead.
Parameter controlName
The control name to check for existence in the collection
Returns
false for disabled controls, true otherwise.
method getRawValue
getRawValue: () => ɵTypedOrUntyped<TControl, ɵFormGroupRawValue<TControl>, any>;
The aggregate value of the
FormGroup
, including any disabled controls.Retrieves all values regardless of disabled status.
method patchValue
patchValue: ( value: ɵFormGroupValue<TControl>, options?: { onlySelf?: boolean; emitEvent?: boolean }) => void;
Patches the value of the
FormGroup
. It accepts an object with control names as keys, 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 group without throwing an error.
### Patch the value for a form group
const form = new FormGroup({first: new FormControl(),last: new FormControl()});console.log(form.value); // {first: null, last: null}form.patchValue({first: 'Nancy'});console.log(form.value); // {first: 'Nancy', last: null}Parameter value
The object that matches the structure of the group.
Parameter options
Configuration options that determine how the control propagates changes and emits events after the value is patched. *
onlySelf
: When true, each change only affects this control and not its parent. Default is true. *emitEvent
: When true or not supplied (the default), both thestatusChanges
andvalueChanges
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 method.
method registerControl
registerControl: { <K extends string & keyof TControl>( name: K, control: TControl[K] ): TControl[K]; ( this: FormGroup<{ [key: string]: AbstractControl<any, any> }>, name: string, control: AbstractControl<any, any> ): AbstractControl<any, any>;};
Registers a control with the group's list of controls. In a strongly-typed group, the control must be in the group's type (possibly as an optional key).
This method does not update the value or validity of the control. Use instead.
Parameter name
The control name to register in the collection
Parameter control
Provides the control for the given name
method removeControl
removeControl: { ( this: FormGroup<{ [key: string]: AbstractControl<any, any> }>, name: string, options?: { emitEvent?: boolean } ): void; <S extends string>( name: ɵOptionalKeys<TControl> & S, options?: { emitEvent?: boolean } ): void;};
method reset
reset: ( value?: ɵTypedOrUntyped<TControl, ɵFormGroupValue<TControl>, any>, options?: { onlySelf?: boolean; emitEvent?: boolean }) => void;
Resets the
FormGroup
, marks all descendantspristine
anduntouched
and sets the value of all descendants to their default values, or null if no defaults were provided.You reset to a specific form state by passing in a map of states that matches the structure of your form, with control names as keys. The state is a standalone value or a form state object with both a value and a disabled status.
Parameter value
Resets the control with an initial value, or an object that defines the initial value and disabled state.
Parameter options
Configuration options that determine how the control propagates changes and emits events when the group is reset. *
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 thestatusChanges
andvalueChanges
observables emit events with the latest status and value when the control is reset. When false, no events are emitted. The configuration options are passed to the method.### Reset the form group values
const form = new FormGroup({first: new FormControl('first name'),last: new FormControl('last name')});console.log(form.value); // {first: 'first name', last: 'last name'}form.reset({ first: 'name', last: 'last name' });console.log(form.value); // {first: 'name', last: 'last name'}### Reset the form group values and disabled status
const form = new FormGroup({first: new FormControl('first name'),last: new FormControl('last name')});form.reset({first: {value: 'name', disabled: true},last: 'last'});console.log(form.value); // {last: 'last'}console.log(form.get('first').status); // 'DISABLED'
method setControl
setControl: { <K extends string & keyof TControl>( name: K, control: TControl[K], options?: { emitEvent?: boolean } ): void; ( this: FormGroup<{ [key: string]: AbstractControl<any, any> }>, name: string, control: AbstractControl<any, any>, options?: { emitEvent?: boolean } ): void;};
Replace an existing control. In a strongly-typed group, the control must be in the group's type (possibly as an optional key).
If a control with a given name does not exist in this
FormGroup
, it will be added.Parameter name
The control name to replace in the collection
Parameter control
Provides the control for the given name
Parameter options
Specifies whether this FormGroup instance should emit events after an existing control is replaced. *
emitEvent
: When true or not supplied (the default), both thestatusChanges
andvalueChanges
observables emit events with the latest status and value when the control is replaced with a new one. When false, no events are emitted.
method setValue
setValue: ( value: ɵFormGroupRawValue<TControl>, options?: { onlySelf?: boolean; emitEvent?: boolean }) => void;
Sets the value of the
FormGroup
. It accepts an object that matches the structure of the group, with control names as keys.### Set the complete value for the form group
const form = new FormGroup({first: new FormControl(),last: new FormControl()});console.log(form.value); // {first: null, last: null}form.setValue({first: 'Nancy', last: 'Drew'});console.log(form.value); // {first: 'Nancy', last: 'Drew'}Parameter value
The new value for the control that matches the structure of the group.
Parameter options
Configuration options that determine how the control propagates changes and emits events after the value changes. The configuration options are passed to the 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 thestatusChanges
andvalueChanges
observables emit events with the latest status and value when the control value is updated. When false, no events are emitted.Throws
When strict checks fail, such as setting the value of a control that doesn't exist or if you exclude a value of a control that does exist.
class FormGroupDirective
class FormGroupDirective extends ControlContainer implements Form, OnChanges, OnDestroy {}
Binds an existing
FormGroup
orFormRecord
to a DOM element.This directive accepts an existing
FormGroup
instance. It will then use thisFormGroup
instance to match any childFormControl
,FormGroup
/FormRecord
, andFormArray
instances to childFormControlName
,FormGroupName
, andFormArrayName
directives.See Also
[Reactive Forms Guide](guide/forms/reactive-forms)
### Register Form Group
The following example registers a
FormGroup
with first name and last name controls, and listens for the *ngSubmit* event when the button is clicked.ReactiveFormsModule
constructor
constructor( validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[], callSetDisabledState?: SetDisabledStateOption);
property control
readonly control: FormGroup<any>;
Returns the
FormGroup
bound to this directive.
property directives
directives: FormControlName[];
Tracks the list of added
FormControlName
instances
property form
form: FormGroup<any>;
Tracks the
FormGroup
bound to this directive.
property formDirective
readonly formDirective: Form;
Returns this directive's instance.
property ngSubmit
ngSubmit: EventEmitter<any>;
Emits an event when the form submission has been triggered.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< FormGroupDirective, '[formGroup]', ['ngForm'], { form: { alias: 'formGroup'; required: false } }, { ngSubmit: 'ngSubmit' }, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< FormGroupDirective, [ { optional: true; self: true }, { optional: true; self: true }, { optional: true } ]>;
property path
readonly path: string[];
Returns an array representing the path to this group. Because this directive always lives at the top level of a form, it always an empty array.
property submitted
submitted: boolean;
Reports whether the form submission has been triggered.
method addControl
addControl: (dir: FormControlName) => FormControl;
Method that sets up the control directive in this group, re-calculates its value and validity, and adds the instance to the internal list of directives.
Parameter dir
The
FormControlName
directive instance.
method addFormArray
addFormArray: (dir: FormArrayName) => void;
Performs the necessary setup when a
FormArrayName
directive instance is added to the view.Parameter dir
The
FormArrayName
directive instance.
method addFormGroup
addFormGroup: (dir: FormGroupName) => void;
Adds a new
FormGroupName
directive instance to the form.Parameter dir
The
FormGroupName
directive instance.
method getControl
getControl: (dir: FormControlName) => FormControl;
Retrieves the
FormControl
instance from the providedFormControlName
directiveParameter dir
The
FormControlName
directive instance.
method getFormArray
getFormArray: (dir: FormArrayName) => FormArray;
Retrieves the
FormArray
for a providedFormArrayName
directive instance.Parameter dir
The
FormArrayName
directive instance.
method getFormGroup
getFormGroup: (dir: FormGroupName) => FormGroup;
Retrieves the
FormGroup
for a providedFormGroupName
directive instanceParameter dir
The
FormGroupName
directive instance.
method ngOnChanges
ngOnChanges: (changes: SimpleChanges) => void;
method ngOnDestroy
ngOnDestroy: () => void;
method onReset
onReset: () => void;
Method called when the "reset" event is triggered on the form.
method onSubmit
onSubmit: ($event: Event) => boolean;
Method called with the "submit" event is triggered on the form. Triggers the
ngSubmit
emitter to emit the "submit" event as its payload.Parameter $event
The "submit" event object
method removeControl
removeControl: (dir: FormControlName) => void;
Removes the
FormControlName
instance from the internal list of directivesParameter dir
The
FormControlName
directive instance.
method removeFormArray
removeFormArray: (dir: FormArrayName) => void;
Performs the necessary cleanup when a
FormArrayName
directive instance is removed from the view.Parameter dir
The
FormArrayName
directive instance.
method removeFormGroup
removeFormGroup: (dir: FormGroupName) => void;
Performs the necessary cleanup when a
FormGroupName
directive instance is removed from the view.Parameter dir
The
FormGroupName
directive instance.
method resetForm
resetForm: (value?: any) => void;
Resets the form to an initial value and resets its submitted status.
Parameter value
The new value for the form.
method updateModel
updateModel: (dir: FormControlName, value: any) => void;
Sets the new value for the provided
FormControlName
directive.Parameter dir
The
FormControlName
directive instance.Parameter value
The new value for the directive's control.
class FormGroupName
class FormGroupName extends AbstractFormGroupDirective implements OnInit, OnDestroy {}
Syncs a nested
FormGroup
orFormRecord
to a DOM element.This directive can only be used with a parent
FormGroupDirective
.It accepts the string name of the nested
FormGroup
orFormRecord
to link, and looks for aFormGroup
orFormRecord
registered with that name in the parentFormGroup
instance you passed intoFormGroupDirective
.Use nested form groups to validate a sub-group of a form separately from the rest or to group the values of certain controls into their own nested object.
See Also
[Reactive Forms Guide](guide/forms/reactive-forms)
### Access the group by name
The following example uses the
AbstractControl.get
method to access the associatedFormGroup
this.form.get('name');### Access individual controls in the group
The following example uses the
AbstractControl.get
method to access individual controls within the group using dot syntax.this.form.get('name.first');### Register a nested
FormGroup
.The following example registers a nested *name*
FormGroup
within an existingFormGroup
, and provides methods to retrieve the nestedFormGroup
and individual controls.ReactiveFormsModule
constructor
constructor( parent: ControlContainer, validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[]);
property name
name: string | number;
Tracks the name of the
FormGroup
bound to the directive. The name corresponds to a key in the parentFormGroup
orFormArray
. Accepts a name as a string or a number. The name in the form of a string is useful for individual forms, while the numerical form allows for form groups to be bound to indices when iterating over groups in aFormArray
.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< FormGroupName, '[formGroupName]', never, { name: { alias: 'formGroupName'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< FormGroupName, [ { optional: true; host: true; skipSelf: true }, { optional: true; self: true }, { optional: true; self: true } ]>;
class FormRecord
class FormRecord< TControl extends AbstractControl = AbstractControl> extends FormGroup<{ [key: string]: TControl;}> {}
Tracks the value and validity state of a collection of
FormControl
instances, each of which has the same value type.FormRecord
is very similar to FormGroup, except it can be used with a dynamic keys, with controls added and removed as needed.FormRecord
accepts one generic argument, which describes the type of the controls it contains.let numbers = new FormRecord({bill: new FormControl('415-123-456')});numbers.addControl('bob', new FormControl('415-234-567'));numbers.removeControl('bill');
class FormResetEvent
class FormResetEvent extends ControlEvent {}
Event fired when a form is reset.
constructor
constructor(source: AbstractControl<any, any>);
property source
readonly source: AbstractControl<any, any>;
class FormsModule
class FormsModule {}
Exports the required providers and directives for template-driven forms, making them available for import by NgModules that import this module.
See Also
[Forms Overview](guide/forms)
[Template-driven Forms Guide](guide/forms)
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<FormsModule, never>;
property ɵinj
static ɵinj: i0.ɵɵInjectorDeclaration<FormsModule>;
property ɵmod
static ɵmod: i0.ɵɵNgModuleDeclaration< FormsModule, [typeof NgModel, typeof NgModelGroup, typeof NgForm], never, [ typeof ɵInternalFormsSharedModule, typeof NgModel, typeof NgModelGroup, typeof NgForm ]>;
method withConfig
static withConfig: (opts: { callSetDisabledState?: SetDisabledStateOption;}) => ModuleWithProviders<FormsModule>;
Provides options for configuring the forms module.
Parameter opts
An object of configuration options *
callSetDisabledState
Configures whether toalways
callsetDisabledState
, which is more correct, or to only call itwhenDisabled
, which is the legacy behavior.
class FormSubmittedEvent
class FormSubmittedEvent extends ControlEvent {}
Event fired when a form is submitted
constructor
constructor(source: AbstractControl<any, any>);
property source
readonly source: AbstractControl<any, any>;
class MaxLengthValidator
class MaxLengthValidator extends AbstractValidatorDirective {}
A directive that adds maximum length validation to controls marked with the
maxlength
attribute. The directive is provided with theNG_VALIDATORS
multi-provider list.See Also
[Form Validation](guide/forms/form-validation)
### Adding a maximum length validator
The following example shows how to add a maximum length validator to an input attached to an ngModel binding.
<input name="firstName" ngModel maxlength="25">ReactiveFormsModule FormsModule
property maxlength
maxlength: string | number;
Tracks changes to the maximum length bound to this directive.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< MaxLengthValidator, '[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]', never, { maxlength: { alias: 'maxlength'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<MaxLengthValidator, never>;
class MaxValidator
class MaxValidator extends AbstractValidatorDirective {}
A directive which installs the MaxValidator for any
formControlName
,formControl
, or control withngModel
that also has amax
attribute.See Also
[Form Validation](guide/forms/form-validation)
### Adding a max validator
The following example shows how to add a max validator to an input attached to an ngModel binding.
<input type="number" ngModel max="4">ReactiveFormsModule FormsModule
property max
max: string | number;
Tracks changes to the max bound to this directive.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< MaxValidator, 'input[type=number][max][formControlName],input[type=number][max][formControl],input[type=number][max][ngModel]', never, { max: { alias: 'max'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<MaxValidator, never>;
class MinLengthValidator
class MinLengthValidator extends AbstractValidatorDirective {}
A directive that adds minimum length validation to controls marked with the
minlength
attribute. The directive is provided with theNG_VALIDATORS
multi-provider list.See Also
[Form Validation](guide/forms/form-validation)
### Adding a minimum length validator
The following example shows how to add a minimum length validator to an input attached to an ngModel binding.
<input name="firstName" ngModel minlength="4">ReactiveFormsModule FormsModule
property minlength
minlength: string | number;
Tracks changes to the minimum length bound to this directive.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< MinLengthValidator, '[minlength][formControlName],[minlength][formControl],[minlength][ngModel]', never, { minlength: { alias: 'minlength'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<MinLengthValidator, never>;
class MinValidator
class MinValidator extends AbstractValidatorDirective {}
A directive which installs the MinValidator for any
formControlName
,formControl
, or control withngModel
that also has amin
attribute.See Also
[Form Validation](guide/forms/form-validation)
### Adding a min validator
The following example shows how to add a min validator to an input attached to an ngModel binding.
<input type="number" ngModel min="4">ReactiveFormsModule FormsModule
property min
min: string | number;
Tracks changes to the min bound to this directive.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< MinValidator, 'input[type=number][min][formControlName],input[type=number][min][formControl],input[type=number][min][ngModel]', never, { min: { alias: 'min'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<MinValidator, never>;
class NgControl
abstract class NgControl extends AbstractControlDirective {}
A base class that all
FormControl
-based directives extend. It binds aFormControl
object to a DOM element.
property name
name: string | number;
The name for the control
property valueAccessor
valueAccessor: ControlValueAccessor;
The value accessor for the control
method viewToModelUpdate
abstract viewToModelUpdate: (newValue: any) => void;
The callback method to update the model from the view when requested
Parameter newValue
The new value for the view
class NgControlStatus
class NgControlStatus extends AbstractControlStatus {}
Directive automatically applied to Angular form controls that sets CSS classes based on control status.
### CSS classes applied
The following classes are applied as the properties become true:
* ng-valid * ng-invalid * ng-pending * ng-pristine * ng-dirty * ng-untouched * ng-touched
ReactiveFormsModule FormsModule
constructor
constructor(cd: NgControl);
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NgControlStatus, '[formControlName],[ngModel],[formControl]', never, {}, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<NgControlStatus, [{ self: true }]>;
class NgControlStatusGroup
class NgControlStatusGroup extends AbstractControlStatus {}
Directive automatically applied to Angular form groups that sets CSS classes based on control status (valid/invalid/dirty/etc). On groups, this includes the additional class ng-submitted.
See Also
ReactiveFormsModule FormsModule
constructor
constructor(cd: ControlContainer);
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NgControlStatusGroup, '[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]', never, {}, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< NgControlStatusGroup, [{ optional: true; self: true }]>;
class NgForm
class NgForm extends ControlContainer implements Form, AfterViewInit {}
Creates a top-level
FormGroup
instance and binds it to a form to track aggregate form value and validation status.As soon as you import the
FormsModule
, this directive becomes active by default on all<form>
tags. You don't need to add a special selector.You optionally export the directive into a local template variable using
ngForm
as the key (ex:#myForm="ngForm"
). This is optional, but useful. Many properties from the underlyingFormGroup
instance are duplicated on the directive itself, so a reference to it gives you access to the aggregate value and validity status of the form, as well as user interaction properties likedirty
andtouched
.To register child controls with the form, use
NgModel
with aname
attribute. You may useNgModelGroup
to create sub-groups within the form.If necessary, listen to the directive's
ngSubmit
event to be notified when the user has triggered a form submission. ThengSubmit
event emits the original form submission event.In template driven forms, all
<form>
tags are automatically tagged asNgForm
. To import theFormsModule
but skip its usage in some forms, for example, to use native HTML5 validation, add thengNoForm
and the<form>
tags won't create anNgForm
directive. In reactive forms, usingngNoForm
is unnecessary because the<form>
tags are inert. In that case, you would refrain from using theformGroup
directive.### Listening for form submission
The following example shows how to capture the form values from the "ngSubmit" event.
### Setting the update options
The following example shows you how to change the "updateOn" option from its default using ngFormOptions.
<form [ngFormOptions]="{updateOn: 'blur'}"><input name="one" ngModel> <!-- this ngModel will update on blur --></form>### Native DOM validation UI
In order to prevent the native DOM form validation UI from interfering with Angular's form validation, Angular automatically adds the
novalidate
attribute on any<form>
wheneverFormModule
orReactiveFormModule
are imported into the application. If you want to explicitly enable native DOM validation UI with Angular forms, you can add thengNativeValidate
attribute to the<form>
element:<form ngNativeValidate>...</form>FormsModule
constructor
constructor( validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[], callSetDisabledState?: SetDisabledStateOption);
property control
readonly control: FormGroup<any>;
The internal
FormGroup
instance.
property controls
readonly controls: { [key: string]: AbstractControl<any, any> };
Returns a map of the controls in this group.
property form
form: FormGroup<any>;
The
FormGroup
instance created for this form.
property formDirective
readonly formDirective: Form;
The directive instance.
property ngSubmit
ngSubmit: EventEmitter<any>;
Event emitter for the "ngSubmit" event
property options
options: { updateOn?: FormHooks };
Tracks options for the
NgForm
instance.**updateOn**: Sets the default
updateOn
value for all childNgModels
below it unless explicitly set by a childNgModel
usingngModelOptions
). Defaults to 'change'. Possible values:'change'
|'blur'
|'submit'
.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NgForm, 'form:not([ngNoForm]):not([formGroup]),ng-form,[ngForm]', ['ngForm'], { options: { alias: 'ngFormOptions'; required: false } }, { ngSubmit: 'ngSubmit' }, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< NgForm, [ { optional: true; self: true }, { optional: true; self: true }, { optional: true } ]>;
property path
readonly path: string[];
Returns an array representing the path to this group. Because this directive always lives at the top level of a form, it is always an empty array.
property submitted
readonly submitted: boolean;
Returns whether the form submission has been triggered.
method addControl
addControl: (dir: NgModel) => void;
Method that sets up the control directive in this group, re-calculates its value and validity, and adds the instance to the internal list of directives.
Parameter dir
The
NgModel
directive instance.
method addFormGroup
addFormGroup: (dir: NgModelGroup) => void;
Adds a new
NgModelGroup
directive instance to the form.Parameter dir
The
NgModelGroup
directive instance.
method getControl
getControl: (dir: NgModel) => FormControl;
Retrieves the
FormControl
instance from the providedNgModel
directive.Parameter dir
The
NgModel
directive instance.
method getFormGroup
getFormGroup: (dir: NgModelGroup) => FormGroup;
Retrieves the
FormGroup
for a providedNgModelGroup
directive instanceParameter dir
The
NgModelGroup
directive instance.
method ngAfterViewInit
ngAfterViewInit: () => void;
method onReset
onReset: () => void;
Method called when the "reset" event is triggered on the form.
method onSubmit
onSubmit: ($event: Event) => boolean;
Method called when the "submit" event is triggered on the form. Triggers the
ngSubmit
emitter to emit the "submit" event as its payload.Parameter $event
The "submit" event object
method removeControl
removeControl: (dir: NgModel) => void;
Removes the
NgModel
instance from the internal list of directivesParameter dir
The
NgModel
directive instance.
method removeFormGroup
removeFormGroup: (dir: NgModelGroup) => void;
Removes the
NgModelGroup
directive instance from the form.Parameter dir
The
NgModelGroup
directive instance.
method resetForm
resetForm: (value?: any) => void;
Resets the form to an initial value and resets its submitted status.
Parameter value
The new value for the form.
method setValue
setValue: (value: { [key: string]: any }) => void;
Sets the value for this
FormGroup
.Parameter value
The new value
method updateModel
updateModel: (dir: NgControl, value: any) => void;
Sets the new value for the provided
NgControl
directive.Parameter dir
The
NgControl
directive instance.Parameter value
The new value for the directive's control.
class NgModel
class NgModel extends NgControl implements OnChanges, OnDestroy {}
Creates a
FormControl
instance from a [domain model](https://en.wikipedia.org/wiki/Domain_model) and binds it to a form control element.The
FormControl
instance tracks the value, user interaction, and validation status of the control and keeps the view synced with the model. If used within a parent form, the directive also registers itself with the form as a child control.This directive is used by itself or as part of a larger form. Use the
ngModel
selector to activate it.It accepts a domain model as an optional
Input
. If you have a one-way binding tongModel
with[]
syntax, changing the domain model's value in the component class sets the value in the view. If you have a two-way binding with[()]
syntax (also known as 'banana-in-a-box syntax'), the value in the UI always syncs back to the domain model in your class.To inspect the properties of the associated
FormControl
(like the validity state), export the directive into a local template variable usingngModel
as the key (ex:#myVar="ngModel"
). You can then access the control using the directive'scontrol
property. However, the most commonly used properties (likevalid
anddirty
) also exist on the control for direct access. See a full list of properties directly available inAbstractControlDirective
.See Also
### Using ngModel on a standalone control
The following examples show a simple standalone control using
ngModel
:When using the
ngModel
within<form>
tags, you'll also need to supply aname
attribute so that the control can be registered with the parent form under that name.In the context of a parent form, it's often unnecessary to include one-way or two-way binding, as the parent form syncs the value for you. You access its properties by exporting it into a local template variable using
ngForm
such as (#f="ngForm"
). Use the variable where needed on form submission.If you do need to populate initial values into your form, using a one-way binding for
ngModel
tends to be sufficient as long as you use the exported form's value rather than the domain model's value on submit.### Using ngModel within a form
The following example shows controls using
ngModel
within a form:### Using a standalone ngModel within a group
The following example shows you how to use a standalone ngModel control within a form. This controls the display of the form, but doesn't contain form data.
<form><input name="login" ngModel placeholder="Login"><input type="checkbox" ngModel [ngModelOptions]="{standalone: true}"> Show more options?</form><!-- form value: {login: ''} -->### Setting the ngModel
name
attribute through optionsThe following example shows you an alternate way to set the name attribute. Here, an attribute identified as name is used within a custom form control component. To still be able to specify the NgModel's name, you must specify it using the
ngModelOptions
input instead.<form><my-custom-form-control name="Nancy" ngModel [ngModelOptions]="{name: 'user'}"></my-custom-form-control></form><!-- form value: {user: ''} -->FormsModule
constructor
constructor( parent: ControlContainer, validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[], valueAccessors: ControlValueAccessor[], _changeDetectorRef?: any, callSetDisabledState?: SetDisabledStateOption);
property control
readonly control: FormControl<any>;
property formDirective
readonly formDirective: any;
The top-level directive for this control if present, otherwise null.
property isDisabled
isDisabled: boolean;
Tracks whether the control is disabled.
property model
model: any;
Tracks the value bound to this directive.
property name
name: string;
Tracks the name bound to the directive. If a parent form exists, it uses this name as a key to retrieve this control's value.
property ngAcceptInputType_isDisabled
static ngAcceptInputType_isDisabled: string | boolean;
property options
options: { name?: string; standalone?: boolean; updateOn?: FormHooks };
Tracks the configuration options for this
ngModel
instance.**name**: An alternative to setting the name attribute on the form control element. See the [example](api/forms/NgModel#using-ngmodel-on-a-standalone-control) for using
NgModel
as a standalone control.**standalone**: When set to true, the
ngModel
will not register itself with its parent form, and acts as if it's not in the form. Defaults to false. If no parent form exists, this option has no effect.**updateOn**: Defines the event upon which the form control value and validity update. Defaults to 'change'. Possible values:
'change'
|'blur'
|'submit'
.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NgModel, '[ngModel]:not([formControlName]):not([formControl])', ['ngModel'], { name: { alias: 'name'; required: false }; isDisabled: { alias: 'disabled'; required: false }; model: { alias: 'ngModel'; required: false }; options: { alias: 'ngModelOptions'; required: false }; }, { update: 'ngModelChange' }, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< NgModel, [ { optional: true; host: true }, { optional: true; self: true }, { optional: true; self: true }, { optional: true; self: true }, { optional: true }, { optional: true } ]>;
property path
readonly path: string[];
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.
property update
update: EventEmitter<any>;
Event emitter for producing the
ngModelChange
event after the view model updates.
property viewModel
viewModel: any;
Internal reference to the view model value.
method ngOnChanges
ngOnChanges: (changes: SimpleChanges) => void;
method ngOnDestroy
ngOnDestroy: () => void;
method viewToModelUpdate
viewToModelUpdate: (newValue: any) => void;
Sets the new value for the view model and emits an
ngModelChange
event.Parameter newValue
The new value emitted by
ngModelChange
.
class NgModelGroup
class NgModelGroup extends AbstractFormGroupDirective implements OnInit, OnDestroy {}
Creates and binds a
FormGroup
instance to a DOM element.This directive can only be used as a child of
NgForm
(within<form>
tags).Use this directive to validate a sub-group of your form separately from the rest of your form, or if some values in your domain model make more sense to consume together in a nested object.
Provide a name for the sub-group and it will become the key for the sub-group in the form's full value. If you need direct access, export the directive into a local template variable using
ngModelGroup
(ex:#myGroup="ngModelGroup"
).### Consuming controls in a grouping
The following example shows you how to combine controls together in a sub-group of the form.
FormsModule
constructor
constructor( parent: ControlContainer, validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[]);
property name
name: string;
Tracks the name of the
NgModelGroup
bound to the directive. The name corresponds to a key in the parentNgForm
.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NgModelGroup, '[ngModelGroup]', ['ngModelGroup'], { name: { alias: 'ngModelGroup'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< NgModelGroup, [ { host: true; skipSelf: true }, { optional: true; self: true }, { optional: true; self: true } ]>;
class NgSelectOption
class NgSelectOption implements OnDestroy {}
Marks
<option>
as dynamic, so Angular can be notified when options change.See Also
ReactiveFormsModule FormsModule
constructor
constructor( _element: ElementRef, _renderer: Renderer2, _select: SelectControlValueAccessor);
property id
id: string;
ID of the option element
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NgSelectOption, 'option', never, { ngValue: { alias: 'ngValue'; required: false }; value: { alias: 'value'; required: false }; }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< NgSelectOption, [null, null, { optional: true; host: true }]>;
method ngOnDestroy
ngOnDestroy: () => void;
class NonNullableFormBuilder
abstract class NonNullableFormBuilder {}
NonNullableFormBuilder
is similar to FormBuilder, but automatically constructed FormControl elements have{nonNullable: true}
and are non-nullable.
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<NonNullableFormBuilder, never>;
property ɵprov
static ɵprov: i0.ɵɵInjectableDeclaration<NonNullableFormBuilder>;
method array
abstract array: <T>( controls: Array<T>, validatorOrOpts?: | ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null) => FormArray<ɵElement<T, never>>;
Similar to
FormBuilder#array
, except any implicitly constructedFormControl
will be non-nullable (i.e. it will havenonNullable
set to true). Note that already-constructed controls will not be altered.
method control
abstract control: <T>( formState: T | FormControlState<T>, validatorOrOpts?: | ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null) => FormControl<T>;
Similar to
FormBuilder#control
, except this overridden version ofcontrol
forcesnonNullable
to betrue
, resulting in the control always being non-nullable.
method group
abstract group: <T extends {}>( controls: T, options?: AbstractControlOptions | null) => FormGroup<{ [K in keyof T]: ɵElement<T[K], never> }>;
Similar to
FormBuilder#group
, except any implicitly constructedFormControl
will be non-nullable (i.e. it will havenonNullable
set to true). Note that already-constructed controls will not be altered.
method record
abstract record: <T>( controls: { [key: string]: T }, options?: AbstractControlOptions | null) => FormRecord<ɵElement<T, never>>;
Similar to
FormBuilder#record
, except any implicitly constructedFormControl
will be non-nullable (i.e. it will havenonNullable
set to true). Note that already-constructed controls will not be altered.
class NumberValueAccessor
class NumberValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor {}
The
ControlValueAccessor
for writing a number value and listening to number input changes. The value accessor is used by theFormControlDirective
,FormControlName
, andNgModel
directives.### Using a number input with a reactive form.
The following example shows how to use a number input with a reactive form.
const totalCountControl = new FormControl();<input type="number" [formControl]="totalCountControl">ReactiveFormsModule FormsModule
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NumberValueAccessor, 'input[type=number][formControlName],input[type=number][formControl],input[type=number][ngModel]', never, {}, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<NumberValueAccessor, never>;
method registerOnChange
registerOnChange: (fn: (_: number | null) => void) => void;
Registers a function called when the control value changes.
method writeValue
writeValue: (value: number) => void;
Sets the "value" property on the input element.
class ɵInternalFormsSharedModule
class ɵInternalFormsSharedModule {}
Internal module used for sharing directives between FormsModule and ReactiveFormsModule
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<ɵInternalFormsSharedModule, never>;
property ɵinj
static ɵinj: i0.ɵɵInjectorDeclaration<ɵInternalFormsSharedModule>;
property ɵmod
static ɵmod: i0.ɵɵNgModuleDeclaration< ɵInternalFormsSharedModule, [ typeof ɵNgNoValidate, typeof NgSelectOption, typeof ɵNgSelectMultipleOption, typeof DefaultValueAccessor, typeof NumberValueAccessor, typeof RangeValueAccessor, typeof CheckboxControlValueAccessor, typeof SelectControlValueAccessor, typeof SelectMultipleControlValueAccessor, typeof RadioControlValueAccessor, typeof NgControlStatus, typeof NgControlStatusGroup, typeof RequiredValidator, typeof MinLengthValidator, typeof MaxLengthValidator, typeof PatternValidator, typeof CheckboxRequiredValidator, typeof EmailValidator, typeof MinValidator, typeof MaxValidator ], never, [ typeof ɵNgNoValidate, typeof NgSelectOption, typeof ɵNgSelectMultipleOption, typeof DefaultValueAccessor, typeof NumberValueAccessor, typeof RangeValueAccessor, typeof CheckboxControlValueAccessor, typeof SelectControlValueAccessor, typeof SelectMultipleControlValueAccessor, typeof RadioControlValueAccessor, typeof NgControlStatus, typeof NgControlStatusGroup, typeof RequiredValidator, typeof MinLengthValidator, typeof MaxLengthValidator, typeof PatternValidator, typeof CheckboxRequiredValidator, typeof EmailValidator, typeof MinValidator, typeof MaxValidator ]>;
class ɵNgNoValidate
class ɵNgNoValidate {}
Adds
novalidate
attribute to all forms by default.novalidate
is used to disable browser's native form validation.If you want to use native validation with Angular forms, just add
ngNativeValidate
attribute:<form ngNativeValidate></form>ReactiveFormsModule FormsModule
class ɵNgSelectMultipleOption
class ɵNgSelectMultipleOption implements OnDestroy {}
Marks
<option>
as dynamic, so Angular can be notified when options change.See Also
SelectMultipleControlValueAccessor
ReactiveFormsModule FormsModule
constructor
constructor( _element: ElementRef, _renderer: Renderer2, _select: SelectMultipleControlValueAccessor);
property id
id: string;
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< ɵNgSelectMultipleOption, 'option', never, { ngValue: { alias: 'ngValue'; required: false }; value: { alias: 'value'; required: false }; }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< ɵNgSelectMultipleOption, [null, null, { optional: true; host: true }]>;
method ngOnDestroy
ngOnDestroy: () => void;
class PatternValidator
class PatternValidator extends AbstractValidatorDirective {}
A directive that adds regex pattern validation to controls marked with the
pattern
attribute. The regex must match the entire control value. The directive is provided with theNG_VALIDATORS
multi-provider list.See Also
[Form Validation](guide/forms/form-validation)
### Adding a pattern validator
The following example shows how to add a pattern validator to an input attached to an ngModel binding.
<input name="firstName" ngModel pattern="[a-zA-Z ]*">ReactiveFormsModule FormsModule
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< PatternValidator, '[pattern][formControlName],[pattern][formControl],[pattern][ngModel]', never, { pattern: { alias: 'pattern'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<PatternValidator, never>;
property pattern
pattern: string | RegExp;
Tracks changes to the pattern bound to this directive.
class PristineChangeEvent
class PristineChangeEvent extends ControlEvent {}
Event fired when the control's pristine state changes (pristine <=> dirty).
constructor
constructor(pristine: boolean, source: AbstractControl<any, any>);
property pristine
readonly pristine: boolean;
property source
readonly source: AbstractControl<any, any>;
class RadioControlValueAccessor
class RadioControlValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor, OnDestroy, OnInit {}
The
ControlValueAccessor
for writing radio control values and listening to radio control changes. The value accessor is used by theFormControlDirective
,FormControlName
, andNgModel
directives.### Using radio buttons with reactive form directives
The follow example shows how to use radio buttons in a reactive form. When using radio buttons in a reactive form, radio buttons in the same group should have the same
formControlName
. Providing aname
attribute is optional.ReactiveFormsModule FormsModule
constructor
constructor( renderer: Renderer2, elementRef: ElementRef, _registry: RadioControlRegistry, _injector: Injector);
property formControlName
formControlName: string;
Tracks the name of the
FormControl
bound to the directive. The name corresponds to a key in the parentFormGroup
orFormArray
.
property name
name: string;
Tracks the name of the radio input element.
property onChange
onChange: () => void;
The registered callback function called when a change event occurs on the input element. Note: we declare
onChange
here (also used as host listener) as a function with no arguments to override theonChange
function (which expects 1 argument) in the parentBaseControlValueAccessor
class.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< RadioControlValueAccessor, 'input[type=radio][formControlName],input[type=radio][formControl],input[type=radio][ngModel]', never, { name: { alias: 'name'; required: false }; formControlName: { alias: 'formControlName'; required: false }; value: { alias: 'value'; required: false }; }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<RadioControlValueAccessor, never>;
property value
value: any;
Tracks the value of the radio input element
method fireUncheck
fireUncheck: (value: any) => void;
Sets the "value" on the radio input element and unchecks it.
Parameter value
method ngOnDestroy
ngOnDestroy: () => void;
method ngOnInit
ngOnInit: () => void;
method registerOnChange
registerOnChange: (fn: (_: any) => {}) => void;
Registers a function called when the control value changes.
method setDisabledState
setDisabledState: (isDisabled: boolean) => void;
method writeValue
writeValue: (value: any) => void;
Sets the "checked" property value on the radio input element.
class RangeValueAccessor
class RangeValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor {}
The
ControlValueAccessor
for writing a range value and listening to range input changes. The value accessor is used by theFormControlDirective
,FormControlName
, andNgModel
directives.### Using a range input with a reactive form
The following example shows how to use a range input with a reactive form.
const ageControl = new FormControl();<input type="range" [formControl]="ageControl">ReactiveFormsModule FormsModule
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< RangeValueAccessor, 'input[type=range][formControlName],input[type=range][formControl],input[type=range][ngModel]', never, {}, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<RangeValueAccessor, never>;
method registerOnChange
registerOnChange: (fn: (_: number | null) => void) => void;
Registers a function called when the control value changes.
method writeValue
writeValue: (value: any) => void;
Sets the "value" property on the input element.
class ReactiveFormsModule
class ReactiveFormsModule {}
Exports the required infrastructure and directives for reactive forms, making them available for import by NgModules that import this module.
See Also
[Forms Overview](guide/forms)
[Reactive Forms Guide](guide/forms/reactive-forms)
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<ReactiveFormsModule, never>;
property ɵinj
static ɵinj: i0.ɵɵInjectorDeclaration<ReactiveFormsModule>;
property ɵmod
static ɵmod: i0.ɵɵNgModuleDeclaration< ReactiveFormsModule, [ typeof FormControlDirective, typeof FormGroupDirective, typeof FormControlName, typeof FormGroupName, typeof FormArrayName ], never, [ typeof ɵInternalFormsSharedModule, typeof FormControlDirective, typeof FormGroupDirective, typeof FormControlName, typeof FormGroupName, typeof FormArrayName ]>;
method withConfig
static withConfig: (opts: { warnOnNgModelWithFormControl?: 'never' | 'once' | 'always'; callSetDisabledState?: SetDisabledStateOption;}) => ModuleWithProviders<ReactiveFormsModule>;
Provides options for configuring the reactive forms module.
Parameter opts
An object of configuration options *
warnOnNgModelWithFormControl
Configures when to emit a warning when anngModel
binding is used with reactive form directives. *callSetDisabledState
Configures whether toalways
callsetDisabledState
, which is more correct, or to only call itwhenDisabled
, which is the legacy behavior.
class RequiredValidator
class RequiredValidator extends AbstractValidatorDirective {}
A directive that adds the
required
validator to any controls marked with therequired
attribute. The directive is provided with theNG_VALIDATORS
multi-provider list.See Also
[Form Validation](guide/forms/form-validation)
### Adding a required validator using template-driven forms
<input name="fullName" ngModel required>FormsModule ReactiveFormsModule
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< RequiredValidator, ':not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]', never, { required: { alias: 'required'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<RequiredValidator, never>;
property required
required: string | boolean;
Tracks changes to the required attribute bound to this directive.
method enabled
enabled: (input: boolean) => boolean;
class SelectControlValueAccessor
class SelectControlValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor {}
The
ControlValueAccessor
for writing select control values and listening to select control changes. The value accessor is used by theFormControlDirective
,FormControlName
, andNgModel
directives.### Using select controls in a reactive form
The following examples show how to use a select control in a reactive form.
### Using select controls in a template-driven form
To use a select in a template-driven form, simply add an
ngModel
and aname
attribute to the main<select>
tag.### Customizing option selection
Angular uses object identity to select option. It's possible for the identities of items to change while the data does not. This can happen, for example, if the items are produced from an RPC to the server, and that RPC is re-run. Even if the data hasn't changed, the second response will produce objects with different identities.
To customize the default option comparison algorithm,
<select>
supportscompareWith
input.compareWith
takes a **function** which has two arguments:option1
andoption2
. IfcompareWith
is given, Angular selects option by the return value of the function.const selectedCountriesControl = new FormControl();<select [compareWith]="compareFn" [formControl]="selectedCountriesControl"><option *ngFor="let country of countries" [ngValue]="country">{{country.name}}</option></select>compareFn(c1: Country, c2: Country): boolean {return c1 && c2 ? c1.id === c2.id : c1 === c2;}**Note:** We listen to the 'change' event because 'input' events aren't fired for selects in IE, see: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event#browser_compatibility
ReactiveFormsModule FormsModule
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< SelectControlValueAccessor, 'select:not([multiple])[formControlName],select:not([multiple])[formControl],select:not([multiple])[ngModel]', never, { compareWith: { alias: 'compareWith'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<SelectControlValueAccessor, never>;
property value
value: any;
method registerOnChange
registerOnChange: (fn: (value: any) => any) => void;
Registers a function called when the control value changes.
method writeValue
writeValue: (value: any) => void;
Sets the "value" property on the select element.
class SelectMultipleControlValueAccessor
class SelectMultipleControlValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor {}
The
ControlValueAccessor
for writing multi-select control values and listening to multi-select control changes. The value accessor is used by theFormControlDirective
,FormControlName
, andNgModel
directives.See Also
### Using a multi-select control
The follow example shows you how to use a multi-select control with a reactive form.
const countryControl = new FormControl();<select multiple name="countries" [formControl]="countryControl"><option *ngFor="let country of countries" [ngValue]="country">{{ country.name }}</option></select>### Customizing option selection
To customize the default option comparison algorithm,
<select>
supportscompareWith
input. See theSelectControlValueAccessor
for usage.ReactiveFormsModule FormsModule
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< SelectMultipleControlValueAccessor, 'select[multiple][formControlName],select[multiple][formControl],select[multiple][ngModel]', never, { compareWith: { alias: 'compareWith'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<SelectMultipleControlValueAccessor, never>;
property value
value: any;
The current value.
method registerOnChange
registerOnChange: (fn: (value: any) => any) => void;
Registers a function called when the control value changes and writes an array of the selected options.
method writeValue
writeValue: (value: any) => void;
Sets the "value" property on one or of more of the select's options.
class StatusChangeEvent
class StatusChangeEvent extends ControlEvent {}
Event fired when the control's status changes.
constructor
constructor(status: FormControlStatus, source: AbstractControl<any, any>);
property source
readonly source: AbstractControl<any, any>;
property status
readonly status: FormControlStatus;
class TouchedChangeEvent
class TouchedChangeEvent extends ControlEvent {}
Event fired when the control's touched status changes (touched <=> untouched).
constructor
constructor(touched: boolean, source: AbstractControl<any, any>);
property source
readonly source: AbstractControl<any, any>;
property touched
readonly touched: boolean;
class UntypedFormBuilder
class UntypedFormBuilder extends FormBuilder {}
UntypedFormBuilder is the same as
FormBuilder
, but it provides untyped controls.
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<UntypedFormBuilder, never>;
property ɵprov
static ɵprov: i0.ɵɵInjectableDeclaration<UntypedFormBuilder>;
method array
array: ( controlsConfig: any[], validatorOrOpts?: | ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null) => UntypedFormArray;
Like
FormBuilder#array
, except the resulting array is untyped.
method control
control: ( formState: any, validatorOrOpts?: ValidatorFn | ValidatorFn[] | FormControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null) => UntypedFormControl;
Like
FormBuilder#control
, except the resulting control is untyped.
method group
group: { ( controlsConfig: { [key: string]: any }, options?: AbstractControlOptions | null ): UntypedFormGroup; ( controlsConfig: { [key: string]: any }, options: { [key: string]: any } ): UntypedFormGroup;};
Like
FormBuilder#group
, except the resulting group is untyped.Deprecated
This API is not typesafe and can result in issues with Closure Compiler renaming. Use the
FormBuilder#group
overload withAbstractControlOptions
instead.
class Validators
class Validators {}
Provides a set of built-in validators that can be used by form controls.
A validator is a function that processes a
FormControl
or collection of controls and returns an error map or null. A null map means that validation has passed.See Also
[Form Validation](guide/forms/form-validation)
method compose
static compose: { (validators: null): null; (validators: ValidatorFn[]): ValidatorFn;};
Compose multiple validators into a single function that returns the union of the individual error maps for the provided control.
Returns
A validator function that returns an error map with the merged error maps of the validators if the validation check fails, otherwise
null
.See Also
method composeAsync
static composeAsync: ( validators: (AsyncValidatorFn | null)[]) => AsyncValidatorFn | null;
Compose multiple async validators into a single function that returns the union of the individual error objects for the provided control.
Returns
A validator function that returns an error map with the merged error objects of the async validators if the validation check fails, otherwise
null
.See Also
method email
static email: (control: AbstractControl) => ValidationErrors | null;
Validator that requires the control's value pass an email validation test.
Tests the value using a [regular expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) pattern suitable for common use cases. The pattern is based on the definition of a valid email address in the [WHATWG HTML specification](https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address) with some enhancements to incorporate more RFC rules (such as rules related to domain names and the lengths of different parts of the address).
The differences from the WHATWG version include: - Disallow
local-part
(the part before the@
symbol) to begin or end with a period (.
). - Disallowlocal-part
to be longer than 64 characters. - Disallow the whole address to be longer than 254 characters.If this pattern does not satisfy your business needs, you can use
Validators.pattern()
to validate the value against a different pattern.### Validate that the field matches a valid email pattern
const control = new FormControl('bad@', Validators.email);console.log(control.errors); // {email: true}Returns
An error map with the
email
property if the validation check fails, otherwisenull
.See Also
method max
static max: (max: number) => ValidatorFn;
Validator that requires the control's value to be less than or equal to the provided number.
### Validate against a maximum of 15
const control = new FormControl(16, Validators.max(15));console.log(control.errors); // {max: {max: 15, actual: 16}}Returns
A validator function that returns an error map with the
max
property if the validation check fails, otherwisenull
.See Also
method maxLength
static maxLength: (maxLength: number) => ValidatorFn;
Validator that requires the length of the control's value to be less than or equal to the provided maximum length. This validator is also provided by default if you use the the HTML5
maxlength
attribute. Note that themaxLength
validator is intended to be used only for types that have a numericlength
property, such as strings or arrays.### Validate that the field has maximum of 5 characters
const control = new FormControl('Angular', Validators.maxLength(5));console.log(control.errors); // {maxlength: {requiredLength: 5, actualLength: 7}}<input maxlength="5">Returns
A validator function that returns an error map with the
maxlength
property if the validation check fails, otherwisenull
.See Also
method min
static min: (min: number) => ValidatorFn;
Validator that requires the control's value to be greater than or equal to the provided number.
### Validate against a minimum of 3
const control = new FormControl(2, Validators.min(3));console.log(control.errors); // {min: {min: 3, actual: 2}}Returns
A validator function that returns an error map with the
min
property if the validation check fails, otherwisenull
.See Also
method minLength
static minLength: (minLength: number) => ValidatorFn;
Validator that requires the length of the control's value to be greater than or equal to the provided minimum length. This validator is also provided by default if you use the the HTML5
minlength
attribute. Note that theminLength
validator is intended to be used only for types that have a numericlength
property, such as strings or arrays. TheminLength
validator logic is also not invoked for values when theirlength
property is 0 (for example in case of an empty string or an empty array), to support optional controls. You can use the standardrequired
validator if empty values should not be considered valid.### Validate that the field has a minimum of 3 characters
const control = new FormControl('ng', Validators.minLength(3));console.log(control.errors); // {minlength: {requiredLength: 3, actualLength: 2}}<input minlength="5">Returns
A validator function that returns an error map with the
minlength
property if the validation check fails, otherwisenull
.See Also
method nullValidator
static nullValidator: (control: AbstractControl) => ValidationErrors | null;
Validator that performs no operation.
See Also
method pattern
static pattern: (pattern: string | RegExp) => ValidatorFn;
Validator that requires the control's value to match a regex pattern. This validator is also provided by default if you use the HTML5
pattern
attribute.### Validate that the field only contains letters or spaces
const control = new FormControl('1', Validators.pattern('[a-zA-Z ]*'));console.log(control.errors); // {pattern: {requiredPattern: '^[a-zA-Z ]*$', actualValue: '1'}}<input pattern="[a-zA-Z ]*">### Pattern matching with the global or sticky flag
RegExp
objects created with theg
ory
flags that are passed intoValidators.pattern
can produce different results on the same input when validations are run consecutively. This is due to how the behavior ofRegExp.prototype.test
is specified in [ECMA-262](https://tc39.es/ecma262/#sec-regexpbuiltinexec) (RegExp
preserves the index of the last match when the global or sticky flag is used). Due to this behavior, it is recommended that when usingValidators.pattern
you **do not** pass in aRegExp
object with either the global or sticky flag enabled.// Not recommended (since the `g` flag is used)const controlOne = new FormControl('1', Validators.pattern(/foo/g));// Goodconst controlTwo = new FormControl('1', Validators.pattern(/foo/));Parameter pattern
A regular expression to be used as is to test the values, or a string. If a string is passed, the
^
character is prepended and the$
character is appended to the provided string (if not already present), and the resulting regular expression is used to test the values.Returns
A validator function that returns an error map with the
pattern
property if the validation check fails, otherwisenull
.See Also
method required
static required: (control: AbstractControl) => ValidationErrors | null;
Validator that requires the control have a non-empty value.
### Validate that the field is non-empty
const control = new FormControl('', Validators.required);console.log(control.errors); // {required: true}Returns
An error map with the
required
property if the validation check fails, otherwisenull
.See Also
method requiredTrue
static requiredTrue: (control: AbstractControl) => ValidationErrors | null;
Validator that requires the control's value be true. This validator is commonly used for required checkboxes.
### Validate that the field value is true
const control = new FormControl('some value', Validators.requiredTrue);console.log(control.errors); // {required: true}Returns
An error map that contains the
required
property set totrue
if the validation check fails, otherwisenull
.See Also
class ValueChangeEvent
class ValueChangeEvent<T> extends ControlEvent<T> {}
Event fired when the value of a control changes.
constructor
constructor(value: {}, source: AbstractControl<any, any>);
property source
readonly source: AbstractControl<any, any>;
property value
readonly value: {};
Interfaces
interface AbstractControlOptions
interface AbstractControlOptions {}
Interface for options provided to an
AbstractControl
.
property asyncValidators
asyncValidators?: AsyncValidatorFn | AsyncValidatorFn[] | null;
The list of async validators applied to control.
property updateOn
updateOn?: 'change' | 'blur' | 'submit';
The event name for control to update upon.
property validators
validators?: ValidatorFn | ValidatorFn[] | null;
The list of validators applied to a control.
interface AsyncValidator
interface AsyncValidator extends Validator {}
An interface implemented by classes that perform asynchronous validation.
### Provide a custom async validator directive
The following example implements the
AsyncValidator
interface to create an async validator directive with a custom error key.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});}}
method validate
validate: ( control: AbstractControl) => Promise<ValidationErrors | null> | Observable<ValidationErrors | null>;
Method that performs async validation against the provided control.
Parameter control
The control to validate against.
Returns
A promise or observable that resolves a map of validation errors if validation fails, otherwise null.
interface AsyncValidatorFn
interface AsyncValidatorFn {}
A function that receives a control and returns a Promise or observable that emits validation errors if present, otherwise null.
call signature
(control: AbstractControl): | Promise<ValidationErrors | null> | Observable<ValidationErrors | null>;
interface ControlValueAccessor
interface ControlValueAccessor {}
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 Also
method registerOnChange
registerOnChange: (fn: any) => void;
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.### Store the change function
The following example stores the provided function as an internal method.
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:
host: {'(change)': '_onChange($event.target.value)'}Parameter fn
The callback function to register
method registerOnTouched
registerOnTouched: (fn: any) => void;
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".### Store the callback function
The following example stores the provided function as an internal method.
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:
host: {'(blur)': '_onTouched()'}Parameter fn
The callback function to register
method setDisabledState
setDisabledState: (isDisabled: boolean) => void;
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.
The following is an example of writing the disabled property to a native DOM element:
setDisabledState(isDisabled: boolean): void {this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);}Parameter isDisabled
The disabled status to set on the element
method writeValue
writeValue: (obj: any) => void;
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.
### Write a value to the element
The following example writes a value to the native DOM element.
writeValue(value: any): void {this._renderer.setProperty(this._elementRef.nativeElement, 'value', value);}Parameter obj
The new value for the element
interface Form
interface Form {}
An interface implemented by
FormGroupDirective
andNgForm
directives.Only used by the
ReactiveFormsModule
andFormsModule
.
method addControl
addControl: (dir: NgControl) => void;
Add a control to this form.
Parameter dir
The control directive to add to the form.
method addFormGroup
addFormGroup: (dir: AbstractFormGroupDirective) => void;
Add a group of controls to this form.
Parameter dir
: The control group directive to add.
method getControl
getControl: (dir: NgControl) => FormControl;
The control directive from which to get the
FormControl
.Parameter dir
: The control directive.
method getFormGroup
getFormGroup: (dir: AbstractFormGroupDirective) => FormGroup;
The
FormGroup
associated with a particularAbstractFormGroupDirective
.Parameter dir
: The form group directive from which to get the
FormGroup
.
method removeControl
removeControl: (dir: NgControl) => void;
Remove a control from this form.
Parameter dir
: The control directive to remove from the form.
method removeFormGroup
removeFormGroup: (dir: AbstractFormGroupDirective) => void;
Remove a group of controls to this form.
Parameter dir
: The control group directive to remove.
method updateModel
updateModel: (dir: NgControl, value: any) => void;
Update the model for a particular control with a new value.
Parameter dir
: The control directive to update.
Parameter value
: The new value for the control.
interface FormControl
interface FormControl<TValue = any> extends AbstractControl<TValue> {}
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
andFormRecord
. It extends theAbstractControl
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 includesnull
because the control can be reset. To change this behavior, setnonNullable
or see the usage notes below.See [usage examples below](#usage-notes).
See Also
[Reactive Forms Guide](guide/forms/reactive-forms)
[Usage Notes](#usage-notes)
ɵFormControlCtor
### 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
anddisabled
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 becomenull
if you callreset
. 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 blurevent
.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 submitevent
.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'
property defaultValue
readonly defaultValue: TValue;
The default value of this FormControl, used whenever the control is reset without an explicit value. See FormControlOptions#nonNullable for more information on configuring a default value.
method getRawValue
getRawValue: () => TValue;
For a simple FormControl, the raw value is equivalent to the value.
method patchValue
patchValue: ( value: TValue, options?: { onlySelf?: boolean; emitEvent?: boolean; emitModelToViewChange?: boolean; emitViewToModelChange?: boolean; }) => void;
Patches the value of a control.
This function is functionally the same as at this level. It exists for symmetry with on
FormGroups
andFormArrays
, where it does behave differently.See Also
FormControl#setValue for options
method registerOnChange
registerOnChange: (fn: Function) => void;
Register a listener for change events.
Parameter fn
The method that is called when the value changes
method registerOnDisabledChange
registerOnDisabledChange: (fn: (isDisabled: boolean) => void) => void;
Register a listener for disabled events.
Parameter fn
The method that is called when the disabled status changes.
method reset
reset: ( formState?: TValue | FormControlState<TValue>, options?: { onlySelf?: boolean; emitEvent?: boolean }) => void;
Resets the form control, marking it
pristine
anduntouched
, and resetting the value. The new value will be the provided value (if passed),null
, or the initial value ifnonNullable
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"Parameter formState
Resets the control with an initial value, or an object that defines the initial value and disabled state.
Parameter options
Configuration options that determine how the control propagates changes and emits events after the value changes.
*
onlySelf
: When true, each change only affects this control, and not its parent. Default is false. *emitEvent
: When true or not supplied (the default), both thestatusChanges
andvalueChanges
observables emit events with the latest status and value when the control is reset. When false, no events are emitted.
method setValue
setValue: ( value: TValue, options?: { onlySelf?: boolean; emitEvent?: boolean; emitModelToViewChange?: boolean; emitViewToModelChange?: boolean; }) => void;
Sets a new value for the form control.
Parameter value
The new value for the control.
Parameter options
Configuration options that determine how the control propagates changes and emits events when the value changes. The configuration options are passed to the 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 thestatusChanges
andvalueChanges
observables emit events with the latest status and value when the control value is updated. When false, no events are emitted. *emitModelToViewChange
: When true or not supplied (the default), each change triggers anonChange
event to update the view. *emitViewToModelChange
: When true or not supplied (the default), each change triggers anngModelChange
event to update the model.
interface FormControlOptions
interface FormControlOptions extends AbstractControlOptions {}
Interface for options provided to a
FormControl
.This interface extends all options from AbstractControlOptions, plus some options unique to
FormControl
.
property initialValueIsDefault
initialValueIsDefault?: boolean;
Deprecated
Use
nonNullable
instead.
property nonNullable
nonNullable?: boolean;
Whether to use the initial value used to construct the
FormControl
as its default value as well. If this option is false or not provided, the default value of a FormControl isnull
. When a FormControl is reset without an explicit value, its value reverts to its default value.
interface FormControlState
interface FormControlState<T> {}
FormControlState is a boxed form value. It is an object with a
value
key and adisabled
key.
interface FormRecord
interface FormRecord<TControl> {}
method addControl
addControl: ( name: string, control: TControl, options?: { emitEvent?: boolean }) => void;
Add a control to this group.
See
FormGroup#addControl
for additional information.
method contains
contains: (controlName: string) => boolean;
Check whether there is an enabled control with the given name in the group.
See
FormGroup#contains
for additional information.
method getRawValue
getRawValue: () => { [key: string]: ɵRawValue<TControl> };
The aggregate value of the
FormRecord
, including any disabled controls.See
FormGroup#getRawValue
for additional information.
method patchValue
patchValue: ( value: { [key: string]: ɵValue<TControl> }, options?: { onlySelf?: boolean; emitEvent?: boolean }) => void;
Patches the value of the
FormRecord
. It accepts an object with control names as keys, and does its best to match the values to the correct controls in the group.See
FormGroup#patchValue
for additional information.
method registerControl
registerControl: (name: string, control: TControl) => TControl;
Registers a control with the records's list of controls.
See
FormGroup#registerControl
for additional information.
method removeControl
removeControl: (name: string, options?: { emitEvent?: boolean }) => void;
Remove a control from this group.
See
FormGroup#removeControl
for additional information.
method reset
reset: ( value?: { [key: string]: ɵValue<TControl> }, options?: { onlySelf?: boolean; emitEvent?: boolean }) => void;
Resets the
FormRecord
, marks all descendantspristine
anduntouched
and sets the value of all descendants to null.See
FormGroup#reset
for additional information.
method setControl
setControl: ( name: string, control: TControl, options?: { emitEvent?: boolean }) => void;
Replace an existing control.
See
FormGroup#setControl
for additional information.
method setValue
setValue: ( value: { [key: string]: ɵValue<TControl> }, options?: { onlySelf?: boolean; emitEvent?: boolean }) => void;
Sets the value of the
FormRecord
. It accepts an object that matches the structure of the group, with control names as keys.See
FormGroup#setValue
for additional information.
interface ɵFormControlCtor
interface ɵFormControlCtor {}
Various available constructors for
FormControl
. Do not use this interface directly. Instead, useFormControl
:const fc = new FormControl('foo');This symbol is prefixed with ɵ to make plain that it is an internal symbol.
property prototype
prototype: FormControl<any>;
The presence of an explicit
prototype
property provides backwards-compatibility for apps that manually inspect the prototype chain.
construct signature
new (): FormControl<any>;
Construct a FormControl with no initial value or validators.
construct signature
new <T = any>( value: FormControlState<T> | T, opts: FormControlOptions & { nonNullable: true; }): FormControl<T>;
Creates a new
FormControl
instance.Parameter formState
Initializes the control with an initial value, or an object that defines the initial value and disabled state.
Parameter validatorOrOpts
A synchronous validator function, or an array of such functions, or a
FormControlOptions
object that contains validation functions and a validation trigger.Parameter asyncValidator
A single async validator or array of async validator functions
construct signature
new <T = any>( value: FormControlState<T> | T, opts: FormControlOptions & { initialValueIsDefault: true; }): FormControl<T>;
Deprecated
Use
nonNullable
instead.
construct signature
new <T = any>( value: FormControlState<T> | T, opts: FormControlOptions, asyncValidator: AsyncValidatorFn | AsyncValidatorFn[]): FormControl<T | null>;
Deprecated
When passing an
options
argument, theasyncValidator
argument has no effect.
construct signature
new <T = any>( value: FormControlState<T> | T, validatorOrOpts?: ValidatorFn | ValidatorFn[] | FormControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null): FormControl<T | null>;
interface Validator
interface Validator {}
An interface implemented by classes that perform synchronous validation.
### Provide a custom validator
The following example implements the
Validator
interface to create a validator directive with a custom error key.@Directive({selector: '[customValidator]',providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}]})class CustomValidatorDirective implements Validator {validate(control: AbstractControl): ValidationErrors|null {return {'custom': true};}}
method registerOnValidatorChange
registerOnValidatorChange: (fn: () => void) => void;
Registers a callback function to call when the validator inputs change.
Parameter fn
The callback function
method validate
validate: (control: AbstractControl) => ValidationErrors | null;
Method that performs synchronous validation against the provided control.
Parameter control
The control to validate against.
Returns
A map of validation errors if validation fails, otherwise null.
interface ValidatorFn
interface ValidatorFn {}
A function that receives a control and synchronously returns a map of validation errors if present, otherwise null.
call signature
(control: AbstractControl): ValidationErrors | null;
Type Aliases
type ControlConfig
type ControlConfig<T> = [ T | FormControlState<T>, (ValidatorFn | ValidatorFn[])?, (AsyncValidatorFn | AsyncValidatorFn[])?];
ControlConfig is a tuple containing a value of type T, plus optional validators and async validators.
type FormControlStatus
type FormControlStatus = 'VALID' | 'INVALID' | 'PENDING' | 'DISABLED';
A form can have several different statuses. Each possible status is returned as a string literal.
* **VALID**: Reports that a control is valid, meaning that no errors exist in the input value. * **INVALID**: Reports that a control is invalid, meaning that an error exists in the input value. * **PENDING**: Reports that a control is pending, meaning that async validation is occurring and errors are not yet available for the input value. * **DISABLED**: Reports that a control is disabled, meaning that the control is exempt from ancestor calculations of validity or value.
type ɵCoerceStrArrToNumArr
type ɵCoerceStrArrToNumArr<S> = S extends [infer Head, ...infer Tail] ? Head extends `${number}` ? [number, ...ɵCoerceStrArrToNumArr<Tail>] : [Head, ...ɵCoerceStrArrToNumArr<Tail>] : [];
CoerceStrArrToNumArr accepts an array of strings, and converts any numeric string to a number.
type ɵElement
type ɵElement<T, N extends null> = [T] extends [FormControl<infer U>] ? FormControl<U> : [T] extends [FormControl<infer U> | undefined] ? FormControl<U> : [T] extends [FormGroup<infer U>] ? FormGroup<U> : [T] extends [FormGroup<infer U> | undefined] ? FormGroup<U> : [T] extends [FormRecord<infer U>] ? FormRecord<U> : [T] extends [FormRecord<infer U> | undefined] ? FormRecord<U> : [T] extends [FormArray<infer U>] ? FormArray<U> : [T] extends [FormArray<infer U> | undefined] ? FormArray<U> : [T] extends [AbstractControl<infer U>] ? AbstractControl<U> : [T] extends [AbstractControl<infer U> | undefined] ? AbstractControl<U> : [T] extends [FormControlState<infer U>] ? FormControl<U | N> : [T] extends [PermissiveControlConfig<infer U>] ? FormControl<Exclude<U, ValidatorConfig | PermissiveAbstractControlOptions> | N> : FormControl<T | N>;
FormBuilder accepts values in various container shapes, as well as raw values. Element returns the appropriate corresponding model class, given the container T. The flag N, if not never, makes the resulting
FormControl
have N in its type.
type ɵFormArrayRawValue
type ɵFormArrayRawValue<T extends AbstractControl<any>> = ɵTypedOrUntyped< T, Array<ɵRawValue<T>>, any[]>;
FormArrayRawValue extracts the type of
.getRawValue()
from a FormArray's element type, and wraps it in an array. The untyped case falls back to any[].Angular uses this type internally to support Typed Forms; do not use it directly.
type ɵFormArrayValue
type ɵFormArrayValue<T extends AbstractControl<any>> = ɵTypedOrUntyped< T, Array<ɵValue<T>>, any[]>;
FormArrayValue extracts the type of
.value
from a FormArray's element type, and wraps it in an array.Angular uses this type internally to support Typed Forms; do not use it directly. The untyped case falls back to any[].
type ɵFormGroupRawValue
type ɵFormGroupRawValue< T extends { [K in keyof T]?: AbstractControl<any>; }> = ɵTypedOrUntyped< T, { [K in keyof T]: ɵRawValue<T[K]>; }, { [key: string]: any; }>;
FormGroupRawValue extracts the type of
.getRawValue()
from a FormGroup's inner object type. The untyped case falls back to {[key: string]: any}.Angular uses this type internally to support Typed Forms; do not use it directly.
For internal use only.
type ɵFormGroupValue
type ɵFormGroupValue< T extends { [K in keyof T]?: AbstractControl<any>; }> = ɵTypedOrUntyped< T, Partial<{ [K in keyof T]: ɵValue<T[K]>; }>, { [key: string]: any; }>;
FormGroupValue extracts the type of
.value
from a FormGroup's inner object type. The untyped case falls back to {[key: string]: any}.Angular uses this type internally to support Typed Forms; do not use it directly.
For internal use only.
type ɵGetProperty
type ɵGetProperty<T, K> = K extends string ? ɵGetProperty<T, ɵCoerceStrArrToNumArr<ɵTokenize<K, '.'>>> : ɵWriteable<K> extends Array<string | number> ? ɵNavigate<T, ɵWriteable<K>> : any;
GetProperty takes a type T and some property names or indices K. If K is a dot-separated string, it is tokenized into an array before proceeding. Then, the type of the nested property at K is computed: T[K[0]][K[1]][K[2]]... This works with both objects, which are indexed by property name, and arrays, which are indexed numerically.
For internal use only.
type ɵNavigate
type ɵNavigate<T, K extends Array<string | number>> = T extends object ? K extends [infer Head, ...infer Tail] ? Head extends keyof T ? Tail extends (string | number)[] ? [] extends Tail ? T[Head] : ɵNavigate<T[Head], Tail> : any : never : any : any;
Navigate takes a type T and an array K, and returns the type of T[K[0]][K[1]][K[2]]...
type ɵOptionalKeys
type ɵOptionalKeys<T> = { [K in keyof T]-?: undefined extends T[K] ? K : never;}[keyof T];
OptionalKeys returns the union of all optional keys in the object.
Angular uses this type internally to support Typed Forms; do not use it directly.
type ɵRawValue
type ɵRawValue<T extends AbstractControl | undefined> = T extends AbstractControl< any, any> ? T['setValue'] extends (v: infer R) => void ? R : never : never;
RawValue gives the raw value type corresponding to a control type.
Note that the resulting type will follow the same rules as
.getRawValue()
on your control, group, or array. This means that all controls inside a group will be required, not optional, regardless of their disabled state.You may also wish to use , which will have
undefined
in group keys (which can be disabled).###
FormGroup
raw value typeImagine you have an interface defining the controls in your group. You can extract the shape of the raw values as follows:
interface PartyFormControls {address: FormControl<string>;}// RawValue operates on controls; the object must be wrapped in a FormGroup.type PartyFormValues = RawValue<FormGroup<PartyFormControls>>;The resulting type is
{address: string}
. (Note the absence ofundefined
.)**Internal: not for public use.**
type ɵTokenize
type ɵTokenize<S extends string, D extends string> = string extends S ? string[] : S extends `${infer T}${D}${infer U}` ? [T, ...ɵTokenize<U, D>] : [S];
Tokenize splits a string literal S by a delimiter D.
type ɵTypedOrUntyped
type ɵTypedOrUntyped<T, Typed, Untyped> = ɵIsAny<T, Untyped, Typed>;
TypedOrUntyped
allows one of two different types to be selected, depending on whether the Forms class it's applied to is typed or not.This is for internal Angular usage to support typed forms; do not directly use it.
type ɵValue
type ɵValue<T extends AbstractControl | undefined> = T extends AbstractControl< any, any> ? T['value'] : never;
Value gives the value type corresponding to a control type.
Note that the resulting type will follow the same rules as
.value
on your control, group, or array, includingundefined
for each group element which might be disabled.If you are trying to extract a value type for a data model, you probably want RawValue, which will not have
undefined
in group keys.###
FormControl
value typeYou can extract the value type of a single control:
type NameControl = FormControl<string>;type NameValue = Value<NameControl>;The resulting type is
string
.###
FormGroup
value typeImagine you have an interface defining the controls in your group. You can extract the shape of the values as follows:
interface PartyFormControls {address: FormControl<string>;}// Value operates on controls; the object must be wrapped in a FormGroup.type PartyFormValues = Value<FormGroup<PartyFormControls>>;The resulting type is
{address: string|undefined}
.###
FormArray
value typeYou can extract values from FormArrays as well:
type GuestNamesControls = FormArray<FormControl<string>>;type NamesValues = Value<GuestNamesControls>;The resulting type is
string[]
.**Internal: not for public use.**
type ɵWriteable
type ɵWriteable<T> = { -readonly [P in keyof T]: T[P];};
ɵWriteable removes readonly from all keys.
type SetDisabledStateOption
type SetDisabledStateOption = 'whenDisabledForLegacyCode' | 'always';
The type for CALL_SET_DISABLED_STATE. If
always
, then ControlValueAccessor will always callsetDisabledState
when attached, which is the most correct behavior. Otherwise, it will only be called when disabled, which is the legacy behavior for compatibility.See Also
type UntypedFormArray
type UntypedFormArray = FormArray<any>;
UntypedFormArray is a non-strongly-typed version of
FormArray
, which permits heterogenous controls.
type UntypedFormControl
type UntypedFormControl = FormControl<any>;
UntypedFormControl is a non-strongly-typed version of
FormControl
.
type UntypedFormGroup
type UntypedFormGroup = FormGroup<any>;
UntypedFormGroup is a non-strongly-typed version of
FormGroup
.
type ValidationErrors
type ValidationErrors = { [key: string]: any;};
Defines the map of errors returned from failed validation checks.
Namespaces
namespace i1
namespace i1 {}
class NgNoValidate
class ɵNgNoValidate {}
Adds
novalidate
attribute to all forms by default.novalidate
is used to disable browser's native form validation.If you want to use native validation with Angular forms, just add
ngNativeValidate
attribute:<form ngNativeValidate></form>ReactiveFormsModule FormsModule
class ɵNgNoValidate
class ɵNgNoValidate {}
Adds
novalidate
attribute to all forms by default.novalidate
is used to disable browser's native form validation.If you want to use native validation with Angular forms, just add
ngNativeValidate
attribute:<form ngNativeValidate></form>ReactiveFormsModule FormsModule
namespace i1_2
namespace i1_2 {}
class NgModel
class NgModel extends NgControl implements OnChanges, OnDestroy {}
Creates a
FormControl
instance from a [domain model](https://en.wikipedia.org/wiki/Domain_model) and binds it to a form control element.The
FormControl
instance tracks the value, user interaction, and validation status of the control and keeps the view synced with the model. If used within a parent form, the directive also registers itself with the form as a child control.This directive is used by itself or as part of a larger form. Use the
ngModel
selector to activate it.It accepts a domain model as an optional
Input
. If you have a one-way binding tongModel
with[]
syntax, changing the domain model's value in the component class sets the value in the view. If you have a two-way binding with[()]
syntax (also known as 'banana-in-a-box syntax'), the value in the UI always syncs back to the domain model in your class.To inspect the properties of the associated
FormControl
(like the validity state), export the directive into a local template variable usingngModel
as the key (ex:#myVar="ngModel"
). You can then access the control using the directive'scontrol
property. However, the most commonly used properties (likevalid
anddirty
) also exist on the control for direct access. See a full list of properties directly available inAbstractControlDirective
.See Also
### Using ngModel on a standalone control
The following examples show a simple standalone control using
ngModel
:When using the
ngModel
within<form>
tags, you'll also need to supply aname
attribute so that the control can be registered with the parent form under that name.In the context of a parent form, it's often unnecessary to include one-way or two-way binding, as the parent form syncs the value for you. You access its properties by exporting it into a local template variable using
ngForm
such as (#f="ngForm"
). Use the variable where needed on form submission.If you do need to populate initial values into your form, using a one-way binding for
ngModel
tends to be sufficient as long as you use the exported form's value rather than the domain model's value on submit.### Using ngModel within a form
The following example shows controls using
ngModel
within a form:### Using a standalone ngModel within a group
The following example shows you how to use a standalone ngModel control within a form. This controls the display of the form, but doesn't contain form data.
<form><input name="login" ngModel placeholder="Login"><input type="checkbox" ngModel [ngModelOptions]="{standalone: true}"> Show more options?</form><!-- form value: {login: ''} -->### Setting the ngModel
name
attribute through optionsThe following example shows you an alternate way to set the name attribute. Here, an attribute identified as name is used within a custom form control component. To still be able to specify the NgModel's name, you must specify it using the
ngModelOptions
input instead.<form><my-custom-form-control name="Nancy" ngModel [ngModelOptions]="{name: 'user'}"></my-custom-form-control></form><!-- form value: {user: ''} -->FormsModule
constructor
constructor( parent: ControlContainer, validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[], valueAccessors: ControlValueAccessor[], _changeDetectorRef?: any, callSetDisabledState?: SetDisabledStateOption);
property control
readonly control: FormControl<any>;
property formDirective
readonly formDirective: any;
The top-level directive for this control if present, otherwise null.
property isDisabled
isDisabled: boolean;
Tracks whether the control is disabled.
property model
model: any;
Tracks the value bound to this directive.
property name
name: string;
Tracks the name bound to the directive. If a parent form exists, it uses this name as a key to retrieve this control's value.
property ngAcceptInputType_isDisabled
static ngAcceptInputType_isDisabled: string | boolean;
property options
options: { name?: string; standalone?: boolean; updateOn?: FormHooks };
Tracks the configuration options for this
ngModel
instance.**name**: An alternative to setting the name attribute on the form control element. See the [example](api/forms/NgModel#using-ngmodel-on-a-standalone-control) for using
NgModel
as a standalone control.**standalone**: When set to true, the
ngModel
will not register itself with its parent form, and acts as if it's not in the form. Defaults to false. If no parent form exists, this option has no effect.**updateOn**: Defines the event upon which the form control value and validity update. Defaults to 'change'. Possible values:
'change'
|'blur'
|'submit'
.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NgModel, '[ngModel]:not([formControlName]):not([formControl])', ['ngModel'], { name: { alias: 'name'; required: false }; isDisabled: { alias: 'disabled'; required: false }; model: { alias: 'ngModel'; required: false }; options: { alias: 'ngModelOptions'; required: false }; }, { update: 'ngModelChange' }, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< NgModel, [ { optional: true; host: true }, { optional: true; self: true }, { optional: true; self: true }, { optional: true; self: true }, { optional: true }, { optional: true } ]>;
property path
readonly path: string[];
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.
property update
update: EventEmitter<any>;
Event emitter for producing the
ngModelChange
event after the view model updates.
property viewModel
viewModel: any;
Internal reference to the view model value.
method ngOnChanges
ngOnChanges: (changes: SimpleChanges) => void;
method ngOnDestroy
ngOnDestroy: () => void;
method viewToModelUpdate
viewToModelUpdate: (newValue: any) => void;
Sets the new value for the view model and emits an
ngModelChange
event.Parameter newValue
The new value emitted by
ngModelChange
.
namespace i10
namespace i10 {}
variable CHECKBOX_REQUIRED_VALIDATOR
const CHECKBOX_REQUIRED_VALIDATOR: Provider;
Provider which adds
CheckboxRequiredValidator
to theNG_VALIDATORS
multi-provider list.
variable EMAIL_VALIDATOR
const EMAIL_VALIDATOR: any;
Provider which adds
EmailValidator
to theNG_VALIDATORS
multi-provider list.
variable MAX_LENGTH_VALIDATOR
const MAX_LENGTH_VALIDATOR: any;
Provider which adds
MaxLengthValidator
to theNG_VALIDATORS
multi-provider list.
variable MAX_VALIDATOR
const MAX_VALIDATOR: Provider;
Provider which adds
MaxValidator
to theNG_VALIDATORS
multi-provider list.
variable MIN_LENGTH_VALIDATOR
const MIN_LENGTH_VALIDATOR: any;
Provider which adds
MinLengthValidator
to theNG_VALIDATORS
multi-provider list.
variable MIN_VALIDATOR
const MIN_VALIDATOR: Provider;
Provider which adds
MinValidator
to theNG_VALIDATORS
multi-provider list.
variable PATTERN_VALIDATOR
const PATTERN_VALIDATOR: any;
Provider which adds
PatternValidator
to theNG_VALIDATORS
multi-provider list.
variable REQUIRED_VALIDATOR
const REQUIRED_VALIDATOR: Provider;
Provider which adds
RequiredValidator
to theNG_VALIDATORS
multi-provider list.
class CheckboxRequiredValidator
class CheckboxRequiredValidator extends RequiredValidator {}
A Directive that adds the
required
validator to checkbox controls marked with therequired
attribute. The directive is provided with theNG_VALIDATORS
multi-provider list.See Also
[Form Validation](guide/forms/form-validation)
### 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>FormsModule ReactiveFormsModule
property ɵdir
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>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<CheckboxRequiredValidator, never>;
class EmailValidator
class EmailValidator extends AbstractValidatorDirective {}
A directive that adds the
email
validator to controls marked with theemail
attribute. The directive is provided with theNG_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 on the [Validators.email page](api/forms/Validators#email).
See Also
[Form Validation](guide/forms/form-validation)
### 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">FormsModule ReactiveFormsModule
property email
email: string | boolean;
Tracks changes to the email attribute bound to this directive.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< EmailValidator, '[email][formControlName],[email][formControl],[email][ngModel]', never, { email: { alias: 'email'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<EmailValidator, never>;
method enabled
enabled: (input: boolean) => boolean;
class MaxLengthValidator
class MaxLengthValidator extends AbstractValidatorDirective {}
A directive that adds maximum length validation to controls marked with the
maxlength
attribute. The directive is provided with theNG_VALIDATORS
multi-provider list.See Also
[Form Validation](guide/forms/form-validation)
### Adding a maximum length validator
The following example shows how to add a maximum length validator to an input attached to an ngModel binding.
<input name="firstName" ngModel maxlength="25">ReactiveFormsModule FormsModule
property maxlength
maxlength: string | number;
Tracks changes to the maximum length bound to this directive.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< MaxLengthValidator, '[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]', never, { maxlength: { alias: 'maxlength'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<MaxLengthValidator, never>;
class MaxValidator
class MaxValidator extends AbstractValidatorDirective {}
A directive which installs the MaxValidator for any
formControlName
,formControl
, or control withngModel
that also has amax
attribute.See Also
[Form Validation](guide/forms/form-validation)
### Adding a max validator
The following example shows how to add a max validator to an input attached to an ngModel binding.
<input type="number" ngModel max="4">ReactiveFormsModule FormsModule
property max
max: string | number;
Tracks changes to the max bound to this directive.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< MaxValidator, 'input[type=number][max][formControlName],input[type=number][max][formControl],input[type=number][max][ngModel]', never, { max: { alias: 'max'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<MaxValidator, never>;
class MinLengthValidator
class MinLengthValidator extends AbstractValidatorDirective {}
A directive that adds minimum length validation to controls marked with the
minlength
attribute. The directive is provided with theNG_VALIDATORS
multi-provider list.See Also
[Form Validation](guide/forms/form-validation)
### Adding a minimum length validator
The following example shows how to add a minimum length validator to an input attached to an ngModel binding.
<input name="firstName" ngModel minlength="4">ReactiveFormsModule FormsModule
property minlength
minlength: string | number;
Tracks changes to the minimum length bound to this directive.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< MinLengthValidator, '[minlength][formControlName],[minlength][formControl],[minlength][ngModel]', never, { minlength: { alias: 'minlength'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<MinLengthValidator, never>;
class MinValidator
class MinValidator extends AbstractValidatorDirective {}
A directive which installs the MinValidator for any
formControlName
,formControl
, or control withngModel
that also has amin
attribute.See Also
[Form Validation](guide/forms/form-validation)
### Adding a min validator
The following example shows how to add a min validator to an input attached to an ngModel binding.
<input type="number" ngModel min="4">ReactiveFormsModule FormsModule
property min
min: string | number;
Tracks changes to the min bound to this directive.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< MinValidator, 'input[type=number][min][formControlName],input[type=number][min][formControl],input[type=number][min][ngModel]', never, { min: { alias: 'min'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<MinValidator, never>;
class PatternValidator
class PatternValidator extends AbstractValidatorDirective {}
A directive that adds regex pattern validation to controls marked with the
pattern
attribute. The regex must match the entire control value. The directive is provided with theNG_VALIDATORS
multi-provider list.See Also
[Form Validation](guide/forms/form-validation)
### Adding a pattern validator
The following example shows how to add a pattern validator to an input attached to an ngModel binding.
<input name="firstName" ngModel pattern="[a-zA-Z ]*">ReactiveFormsModule FormsModule
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< PatternValidator, '[pattern][formControlName],[pattern][formControl],[pattern][ngModel]', never, { pattern: { alias: 'pattern'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<PatternValidator, never>;
property pattern
pattern: string | RegExp;
Tracks changes to the pattern bound to this directive.
class RequiredValidator
class RequiredValidator extends AbstractValidatorDirective {}
A directive that adds the
required
validator to any controls marked with therequired
attribute. The directive is provided with theNG_VALIDATORS
multi-provider list.See Also
[Form Validation](guide/forms/form-validation)
### Adding a required validator using template-driven forms
<input name="fullName" ngModel required>FormsModule ReactiveFormsModule
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< RequiredValidator, ':not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]', never, { required: { alias: 'required'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<RequiredValidator, never>;
property required
required: string | boolean;
Tracks changes to the required attribute bound to this directive.
method enabled
enabled: (input: boolean) => boolean;
interface AsyncValidator
interface AsyncValidator extends Validator {}
An interface implemented by classes that perform asynchronous validation.
### Provide a custom async validator directive
The following example implements the
AsyncValidator
interface to create an async validator directive with a custom error key.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});}}
method validate
validate: ( control: AbstractControl) => Promise<ValidationErrors | null> | Observable<ValidationErrors | null>;
Method that performs async validation against the provided control.
Parameter control
The control to validate against.
Returns
A promise or observable that resolves a map of validation errors if validation fails, otherwise null.
interface AsyncValidatorFn
interface AsyncValidatorFn {}
A function that receives a control and returns a Promise or observable that emits validation errors if present, otherwise null.
call signature
(control: AbstractControl): | Promise<ValidationErrors | null> | Observable<ValidationErrors | null>;
interface Validator
interface Validator {}
An interface implemented by classes that perform synchronous validation.
### Provide a custom validator
The following example implements the
Validator
interface to create a validator directive with a custom error key.@Directive({selector: '[customValidator]',providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}]})class CustomValidatorDirective implements Validator {validate(control: AbstractControl): ValidationErrors|null {return {'custom': true};}}
method registerOnValidatorChange
registerOnValidatorChange: (fn: () => void) => void;
Registers a callback function to call when the validator inputs change.
Parameter fn
The callback function
method validate
validate: (control: AbstractControl) => ValidationErrors | null;
Method that performs synchronous validation against the provided control.
Parameter control
The control to validate against.
Returns
A map of validation errors if validation fails, otherwise null.
interface ValidatorFn
interface ValidatorFn {}
A function that receives a control and synchronously returns a map of validation errors if present, otherwise null.
call signature
(control: AbstractControl): ValidationErrors | null;
type ValidationErrors
type ValidationErrors = { [key: string]: any;};
Defines the map of errors returned from failed validation checks.
namespace i2
namespace i2 {}
class NgSelectOption
class NgSelectOption implements OnDestroy {}
Marks
<option>
as dynamic, so Angular can be notified when options change.See Also
ReactiveFormsModule FormsModule
constructor
constructor( _element: ElementRef, _renderer: Renderer2, _select: SelectControlValueAccessor);
property id
id: string;
ID of the option element
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NgSelectOption, 'option', never, { ngValue: { alias: 'ngValue'; required: false }; value: { alias: 'value'; required: false }; }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< NgSelectOption, [null, null, { optional: true; host: true }]>;
method ngOnDestroy
ngOnDestroy: () => void;
class SelectControlValueAccessor
class SelectControlValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor {}
The
ControlValueAccessor
for writing select control values and listening to select control changes. The value accessor is used by theFormControlDirective
,FormControlName
, andNgModel
directives.### Using select controls in a reactive form
The following examples show how to use a select control in a reactive form.
### Using select controls in a template-driven form
To use a select in a template-driven form, simply add an
ngModel
and aname
attribute to the main<select>
tag.### Customizing option selection
Angular uses object identity to select option. It's possible for the identities of items to change while the data does not. This can happen, for example, if the items are produced from an RPC to the server, and that RPC is re-run. Even if the data hasn't changed, the second response will produce objects with different identities.
To customize the default option comparison algorithm,
<select>
supportscompareWith
input.compareWith
takes a **function** which has two arguments:option1
andoption2
. IfcompareWith
is given, Angular selects option by the return value of the function.const selectedCountriesControl = new FormControl();<select [compareWith]="compareFn" [formControl]="selectedCountriesControl"><option *ngFor="let country of countries" [ngValue]="country">{{country.name}}</option></select>compareFn(c1: Country, c2: Country): boolean {return c1 && c2 ? c1.id === c2.id : c1 === c2;}**Note:** We listen to the 'change' event because 'input' events aren't fired for selects in IE, see: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event#browser_compatibility
ReactiveFormsModule FormsModule
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< SelectControlValueAccessor, 'select:not([multiple])[formControlName],select:not([multiple])[formControl],select:not([multiple])[ngModel]', never, { compareWith: { alias: 'compareWith'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<SelectControlValueAccessor, never>;
property value
value: any;
method registerOnChange
registerOnChange: (fn: (value: any) => any) => void;
Registers a function called when the control value changes.
method writeValue
writeValue: (value: any) => void;
Sets the "value" property on the select element.
namespace i2_2
namespace i2_2 {}
variable modelGroupProvider
const modelGroupProvider: any;
class NgModelGroup
class NgModelGroup extends AbstractFormGroupDirective implements OnInit, OnDestroy {}
Creates and binds a
FormGroup
instance to a DOM element.This directive can only be used as a child of
NgForm
(within<form>
tags).Use this directive to validate a sub-group of your form separately from the rest of your form, or if some values in your domain model make more sense to consume together in a nested object.
Provide a name for the sub-group and it will become the key for the sub-group in the form's full value. If you need direct access, export the directive into a local template variable using
ngModelGroup
(ex:#myGroup="ngModelGroup"
).### Consuming controls in a grouping
The following example shows you how to combine controls together in a sub-group of the form.
FormsModule
constructor
constructor( parent: ControlContainer, validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[]);
property name
name: string;
Tracks the name of the
NgModelGroup
bound to the directive. The name corresponds to a key in the parentNgForm
.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NgModelGroup, '[ngModelGroup]', ['ngModelGroup'], { name: { alias: 'ngModelGroup'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< NgModelGroup, [ { host: true; skipSelf: true }, { optional: true; self: true }, { optional: true; self: true } ]>;
namespace i3
namespace i3 {}
class NgSelectMultipleOption
class ɵNgSelectMultipleOption implements OnDestroy {}
Marks
<option>
as dynamic, so Angular can be notified when options change.See Also
SelectMultipleControlValueAccessor
ReactiveFormsModule FormsModule
constructor
constructor( _element: ElementRef, _renderer: Renderer2, _select: SelectMultipleControlValueAccessor);
property id
id: string;
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< ɵNgSelectMultipleOption, 'option', never, { ngValue: { alias: 'ngValue'; required: false }; value: { alias: 'value'; required: false }; }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< ɵNgSelectMultipleOption, [null, null, { optional: true; host: true }]>;
method ngOnDestroy
ngOnDestroy: () => void;
class ɵNgSelectMultipleOption
class ɵNgSelectMultipleOption implements OnDestroy {}
Marks
<option>
as dynamic, so Angular can be notified when options change.See Also
SelectMultipleControlValueAccessor
ReactiveFormsModule FormsModule
constructor
constructor( _element: ElementRef, _renderer: Renderer2, _select: SelectMultipleControlValueAccessor);
property id
id: string;
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< ɵNgSelectMultipleOption, 'option', never, { ngValue: { alias: 'ngValue'; required: false }; value: { alias: 'value'; required: false }; }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< ɵNgSelectMultipleOption, [null, null, { optional: true; host: true }]>;
method ngOnDestroy
ngOnDestroy: () => void;
class SelectMultipleControlValueAccessor
class SelectMultipleControlValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor {}
The
ControlValueAccessor
for writing multi-select control values and listening to multi-select control changes. The value accessor is used by theFormControlDirective
,FormControlName
, andNgModel
directives.See Also
### Using a multi-select control
The follow example shows you how to use a multi-select control with a reactive form.
const countryControl = new FormControl();<select multiple name="countries" [formControl]="countryControl"><option *ngFor="let country of countries" [ngValue]="country">{{ country.name }}</option></select>### Customizing option selection
To customize the default option comparison algorithm,
<select>
supportscompareWith
input. See theSelectControlValueAccessor
for usage.ReactiveFormsModule FormsModule
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< SelectMultipleControlValueAccessor, 'select[multiple][formControlName],select[multiple][formControl],select[multiple][ngModel]', never, { compareWith: { alias: 'compareWith'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<SelectMultipleControlValueAccessor, never>;
property value
value: any;
The current value.
method registerOnChange
registerOnChange: (fn: (value: any) => any) => void;
Registers a function called when the control value changes and writes an array of the selected options.
method writeValue
writeValue: (value: any) => void;
Sets the "value" property on one or of more of the select's options.
namespace i3_2
namespace i3_2 {}
class NgForm
class NgForm extends ControlContainer implements Form, AfterViewInit {}
Creates a top-level
FormGroup
instance and binds it to a form to track aggregate form value and validation status.As soon as you import the
FormsModule
, this directive becomes active by default on all<form>
tags. You don't need to add a special selector.You optionally export the directive into a local template variable using
ngForm
as the key (ex:#myForm="ngForm"
). This is optional, but useful. Many properties from the underlyingFormGroup
instance are duplicated on the directive itself, so a reference to it gives you access to the aggregate value and validity status of the form, as well as user interaction properties likedirty
andtouched
.To register child controls with the form, use
NgModel
with aname
attribute. You may useNgModelGroup
to create sub-groups within the form.If necessary, listen to the directive's
ngSubmit
event to be notified when the user has triggered a form submission. ThengSubmit
event emits the original form submission event.In template driven forms, all
<form>
tags are automatically tagged asNgForm
. To import theFormsModule
but skip its usage in some forms, for example, to use native HTML5 validation, add thengNoForm
and the<form>
tags won't create anNgForm
directive. In reactive forms, usingngNoForm
is unnecessary because the<form>
tags are inert. In that case, you would refrain from using theformGroup
directive.### Listening for form submission
The following example shows how to capture the form values from the "ngSubmit" event.
### Setting the update options
The following example shows you how to change the "updateOn" option from its default using ngFormOptions.
<form [ngFormOptions]="{updateOn: 'blur'}"><input name="one" ngModel> <!-- this ngModel will update on blur --></form>### Native DOM validation UI
In order to prevent the native DOM form validation UI from interfering with Angular's form validation, Angular automatically adds the
novalidate
attribute on any<form>
wheneverFormModule
orReactiveFormModule
are imported into the application. If you want to explicitly enable native DOM validation UI with Angular forms, you can add thengNativeValidate
attribute to the<form>
element:<form ngNativeValidate>...</form>FormsModule
constructor
constructor( validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[], callSetDisabledState?: SetDisabledStateOption);
property control
readonly control: FormGroup<any>;
The internal
FormGroup
instance.
property controls
readonly controls: { [key: string]: AbstractControl<any, any> };
Returns a map of the controls in this group.
property form
form: FormGroup<any>;
The
FormGroup
instance created for this form.
property formDirective
readonly formDirective: Form;
The directive instance.
property ngSubmit
ngSubmit: EventEmitter<any>;
Event emitter for the "ngSubmit" event
property options
options: { updateOn?: FormHooks };
Tracks options for the
NgForm
instance.**updateOn**: Sets the default
updateOn
value for all childNgModels
below it unless explicitly set by a childNgModel
usingngModelOptions
). Defaults to 'change'. Possible values:'change'
|'blur'
|'submit'
.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NgForm, 'form:not([ngNoForm]):not([formGroup]),ng-form,[ngForm]', ['ngForm'], { options: { alias: 'ngFormOptions'; required: false } }, { ngSubmit: 'ngSubmit' }, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< NgForm, [ { optional: true; self: true }, { optional: true; self: true }, { optional: true } ]>;
property path
readonly path: string[];
Returns an array representing the path to this group. Because this directive always lives at the top level of a form, it is always an empty array.
property submitted
readonly submitted: boolean;
Returns whether the form submission has been triggered.
method addControl
addControl: (dir: NgModel) => void;
Method that sets up the control directive in this group, re-calculates its value and validity, and adds the instance to the internal list of directives.
Parameter dir
The
NgModel
directive instance.
method addFormGroup
addFormGroup: (dir: NgModelGroup) => void;
Adds a new
NgModelGroup
directive instance to the form.Parameter dir
The
NgModelGroup
directive instance.
method getControl
getControl: (dir: NgModel) => FormControl;
Retrieves the
FormControl
instance from the providedNgModel
directive.Parameter dir
The
NgModel
directive instance.
method getFormGroup
getFormGroup: (dir: NgModelGroup) => FormGroup;
Retrieves the
FormGroup
for a providedNgModelGroup
directive instanceParameter dir
The
NgModelGroup
directive instance.
method ngAfterViewInit
ngAfterViewInit: () => void;
method onReset
onReset: () => void;
Method called when the "reset" event is triggered on the form.
method onSubmit
onSubmit: ($event: Event) => boolean;
Method called when the "submit" event is triggered on the form. Triggers the
ngSubmit
emitter to emit the "submit" event as its payload.Parameter $event
The "submit" event object
method removeControl
removeControl: (dir: NgModel) => void;
Removes the
NgModel
instance from the internal list of directivesParameter dir
The
NgModel
directive instance.
method removeFormGroup
removeFormGroup: (dir: NgModelGroup) => void;
Removes the
NgModelGroup
directive instance from the form.Parameter dir
The
NgModelGroup
directive instance.
method resetForm
resetForm: (value?: any) => void;
Resets the form to an initial value and resets its submitted status.
Parameter value
The new value for the form.
method setValue
setValue: (value: { [key: string]: any }) => void;
Sets the value for this
FormGroup
.Parameter value
The new value
method updateModel
updateModel: (dir: NgControl, value: any) => void;
Sets the new value for the provided
NgControl
directive.Parameter dir
The
NgControl
directive instance.Parameter value
The new value for the directive's control.
namespace i4
namespace i4 {}
variable COMPOSITION_BUFFER_MODE
const COMPOSITION_BUFFER_MODE: InjectionToken<boolean>;
Provide this token to control if form directives buffer IME input until the "compositionend" event occurs.
variable DEFAULT_VALUE_ACCESSOR
const DEFAULT_VALUE_ACCESSOR: Provider;
class DefaultValueAccessor
class DefaultValueAccessor extends BaseControlValueAccessor implements ControlValueAccessor {}
The default
ControlValueAccessor
for writing a value and listening to changes on input elements. The accessor is used by theFormControlDirective
,FormControlName
, andNgModel
directives.### 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).
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 thengDefaultControl
attribute as shown below.<custom-input-component ngDefaultControl [(ngModel)]="value"></custom-input-component>ReactiveFormsModule FormsModule
constructor
constructor( renderer: Renderer2, elementRef: ElementRef, _compositionMode: boolean);
property ɵdir
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>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< DefaultValueAccessor, [null, null, { optional: true }]>;
method writeValue
writeValue: (value: any) => void;
Sets the "value" property on the input element.
namespace i4_2
namespace i4_2 {}
variable CALL_SET_DISABLED_STATE
const CALL_SET_DISABLED_STATE: InjectionToken<SetDisabledStateOption>;
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 Also
variable NG_MODEL_WITH_FORM_CONTROL_WARNING
const NG_MODEL_WITH_FORM_CONTROL_WARNING: InjectionToken<unknown>;
Token to provide to turn off the ngModel warning on formControl and formControlName.
variable REACTIVE_DRIVEN_DIRECTIVES
const REACTIVE_DRIVEN_DIRECTIVES: Type<any>[];
variable SHARED_FORM_DIRECTIVES
const SHARED_FORM_DIRECTIVES: Type<any>[];
variable TEMPLATE_DRIVEN_DIRECTIVES
const TEMPLATE_DRIVEN_DIRECTIVES: Type<any>[];
class CheckboxControlValueAccessor
class CheckboxControlValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor {}
A
ControlValueAccessor
for writing a value and listening to changes on a checkbox input element.### Using a checkbox with a reactive form.
The following example shows how to use a checkbox with a reactive form.
const rememberLoginControl = new FormControl();<input type="checkbox" [formControl]="rememberLoginControl">ReactiveFormsModule FormsModule
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< CheckboxControlValueAccessor, 'input[type=checkbox][formControlName],input[type=checkbox][formControl],input[type=checkbox][ngModel]', never, {}, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<CheckboxControlValueAccessor, never>;
method writeValue
writeValue: (value: any) => void;
Sets the "checked" property on the input element.
class DefaultValueAccessor
class DefaultValueAccessor extends BaseControlValueAccessor implements ControlValueAccessor {}
The default
ControlValueAccessor
for writing a value and listening to changes on input elements. The accessor is used by theFormControlDirective
,FormControlName
, andNgModel
directives.### 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).
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 thengDefaultControl
attribute as shown below.<custom-input-component ngDefaultControl [(ngModel)]="value"></custom-input-component>ReactiveFormsModule FormsModule
constructor
constructor( renderer: Renderer2, elementRef: ElementRef, _compositionMode: boolean);
property ɵdir
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>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< DefaultValueAccessor, [null, null, { optional: true }]>;
method writeValue
writeValue: (value: any) => void;
Sets the "value" property on the input element.
class FormArrayName
class FormArrayName extends ControlContainer implements OnInit, OnDestroy {}
Syncs a nested
FormArray
to a DOM element.This directive is designed to be used with a parent
FormGroupDirective
(selector:[formGroup]
).It accepts the string name of the nested
FormArray
you want to link, and will look for aFormArray
registered with that name in the parentFormGroup
instance you passed intoFormGroupDirective
.See Also
[Reactive Forms Guide](guide/forms/reactive-forms)
### Example
ReactiveFormsModule
constructor
constructor( parent: ControlContainer, validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[]);
property control
readonly control: FormArray<any>;
The
FormArray
bound to this directive.
property formDirective
readonly formDirective: FormGroupDirective;
The top-level directive for this group if present, otherwise null.
property name
name: string | number;
Tracks the name of the
FormArray
bound to the directive. The name corresponds to a key in the parentFormGroup
orFormArray
. Accepts a name as a string or a number. The name in the form of a string is useful for individual forms, while the numerical form allows for form arrays to be bound to indices when iterating over arrays in aFormArray
.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< FormArrayName, '[formArrayName]', never, { name: { alias: 'formArrayName'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< FormArrayName, [ { optional: true; host: true; skipSelf: true }, { optional: true; self: true }, { optional: true; self: true } ]>;
property path
readonly path: string[];
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.
method ngOnDestroy
ngOnDestroy: () => void;
A lifecycle method called before the directive's instance is destroyed. For internal use only.
method ngOnInit
ngOnInit: () => void;
A lifecycle method called when the directive's inputs are initialized. For internal use only.
Throws
If the directive does not have a valid parent.
class FormControlDirective
class FormControlDirective extends NgControl implements OnChanges, OnDestroy {}
Synchronizes a standalone
FormControl
instance to a form control element.Note that support for using the
ngModel
input property andngModelChange
event with reactive form directives was deprecated in Angular v6 and is scheduled for removal in a future version of Angular.See Also
[Reactive Forms Guide](guide/forms/reactive-forms)
The following example shows how to register a standalone control and set its value.
ReactiveFormsModule
constructor
constructor( validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[], valueAccessors: ControlValueAccessor[], _ngModelWarningConfig: string, callSetDisabledState?: SetDisabledStateOption);
property control
readonly control: FormControl<any>;
The
FormControl
bound to this directive.
property form
form: FormControl<any>;
Tracks the
FormControl
instance bound to the directive.
property model
model: any;
Deprecated
as of v6
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< FormControlDirective, '[formControl]', ['ngForm'], { form: { alias: 'formControl'; required: false }; isDisabled: { alias: 'disabled'; required: false }; model: { alias: 'ngModel'; required: false }; }, { update: 'ngModelChange' }, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< FormControlDirective, [ { optional: true; self: true }, { optional: true; self: true }, { optional: true; self: true }, { optional: true }, { optional: true } ]>;
property path
readonly path: string[];
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.
property update
update: EventEmitter<any>;
Deprecated
as of v6
property viewModel
viewModel: any;
Internal reference to the view model value.
method ngOnChanges
ngOnChanges: (changes: SimpleChanges) => void;
method ngOnDestroy
ngOnDestroy: () => void;
method viewToModelUpdate
viewToModelUpdate: (newValue: any) => void;
Sets the new value for the view model and emits an
ngModelChange
event.Parameter newValue
The new value for the view model.
class FormControlName
class FormControlName extends NgControl implements OnChanges, OnDestroy {}
Syncs a
FormControl
in an existingFormGroup
to a form control element by name.See Also
[Reactive Forms Guide](guide/forms/reactive-forms)
### Register
FormControl
within a groupThe following example shows how to register multiple form controls within a form group and set their value.
To see
formControlName
examples with different form control types, see:* Radio buttons:
RadioControlValueAccessor
* Selects:SelectControlValueAccessor
### Use with ngModel is deprecated
Support for using the
ngModel
input property andngModelChange
event with reactive form directives has been deprecated in Angular v6 and is scheduled for removal in a future version of Angular.ReactiveFormsModule
constructor
constructor( parent: ControlContainer, validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[], valueAccessors: ControlValueAccessor[], _ngModelWarningConfig: string);
property control
readonly control: FormControl<any>;
Tracks the
FormControl
instance bound to the directive.
property formDirective
readonly formDirective: any;
The top-level directive for this group if present, otherwise null.
property model
model: any;
Deprecated
as of v6
property name
name: string | number;
Tracks the name of the
FormControl
bound to the directive. The name corresponds to a key in the parentFormGroup
orFormArray
. Accepts a name as a string or a number. The name in the form of a string is useful for individual forms, while the numerical form allows for form controls to be bound to indices when iterating over controls in aFormArray
.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< FormControlName, '[formControlName]', never, { name: { alias: 'formControlName'; required: false }; isDisabled: { alias: 'disabled'; required: false }; model: { alias: 'ngModel'; required: false }; }, { update: 'ngModelChange' }, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< FormControlName, [ { optional: true; host: true; skipSelf: true }, { optional: true; self: true }, { optional: true; self: true }, { optional: true; self: true }, { optional: true } ]>;
property path
readonly path: string[];
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.
property update
update: EventEmitter<any>;
Deprecated
as of v6
method ngOnChanges
ngOnChanges: (changes: SimpleChanges) => void;
method ngOnDestroy
ngOnDestroy: () => void;
method viewToModelUpdate
viewToModelUpdate: (newValue: any) => void;
Sets the new value for the view model and emits an
ngModelChange
event.Parameter newValue
The new value for the view model.
class FormGroupDirective
class FormGroupDirective extends ControlContainer implements Form, OnChanges, OnDestroy {}
Binds an existing
FormGroup
orFormRecord
to a DOM element.This directive accepts an existing
FormGroup
instance. It will then use thisFormGroup
instance to match any childFormControl
,FormGroup
/FormRecord
, andFormArray
instances to childFormControlName
,FormGroupName
, andFormArrayName
directives.See Also
[Reactive Forms Guide](guide/forms/reactive-forms)
### Register Form Group
The following example registers a
FormGroup
with first name and last name controls, and listens for the *ngSubmit* event when the button is clicked.ReactiveFormsModule
constructor
constructor( validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[], callSetDisabledState?: SetDisabledStateOption);
property control
readonly control: FormGroup<any>;
Returns the
FormGroup
bound to this directive.
property directives
directives: FormControlName[];
Tracks the list of added
FormControlName
instances
property form
form: FormGroup<any>;
Tracks the
FormGroup
bound to this directive.
property formDirective
readonly formDirective: Form;
Returns this directive's instance.
property ngSubmit
ngSubmit: EventEmitter<any>;
Emits an event when the form submission has been triggered.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< FormGroupDirective, '[formGroup]', ['ngForm'], { form: { alias: 'formGroup'; required: false } }, { ngSubmit: 'ngSubmit' }, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< FormGroupDirective, [ { optional: true; self: true }, { optional: true; self: true }, { optional: true } ]>;
property path
readonly path: string[];
Returns an array representing the path to this group. Because this directive always lives at the top level of a form, it always an empty array.
property submitted
submitted: boolean;
Reports whether the form submission has been triggered.
method addControl
addControl: (dir: FormControlName) => FormControl;
Method that sets up the control directive in this group, re-calculates its value and validity, and adds the instance to the internal list of directives.
Parameter dir
The
FormControlName
directive instance.
method addFormArray
addFormArray: (dir: FormArrayName) => void;
Performs the necessary setup when a
FormArrayName
directive instance is added to the view.Parameter dir
The
FormArrayName
directive instance.
method addFormGroup
addFormGroup: (dir: FormGroupName) => void;
Adds a new
FormGroupName
directive instance to the form.Parameter dir
The
FormGroupName
directive instance.
method getControl
getControl: (dir: FormControlName) => FormControl;
Retrieves the
FormControl
instance from the providedFormControlName
directiveParameter dir
The
FormControlName
directive instance.
method getFormArray
getFormArray: (dir: FormArrayName) => FormArray;
Retrieves the
FormArray
for a providedFormArrayName
directive instance.Parameter dir
The
FormArrayName
directive instance.
method getFormGroup
getFormGroup: (dir: FormGroupName) => FormGroup;
Retrieves the
FormGroup
for a providedFormGroupName
directive instanceParameter dir
The
FormGroupName
directive instance.
method ngOnChanges
ngOnChanges: (changes: SimpleChanges) => void;
method ngOnDestroy
ngOnDestroy: () => void;
method onReset
onReset: () => void;
Method called when the "reset" event is triggered on the form.
method onSubmit
onSubmit: ($event: Event) => boolean;
Method called with the "submit" event is triggered on the form. Triggers the
ngSubmit
emitter to emit the "submit" event as its payload.Parameter $event
The "submit" event object
method removeControl
removeControl: (dir: FormControlName) => void;
Removes the
FormControlName
instance from the internal list of directivesParameter dir
The
FormControlName
directive instance.
method removeFormArray
removeFormArray: (dir: FormArrayName) => void;
Performs the necessary cleanup when a
FormArrayName
directive instance is removed from the view.Parameter dir
The
FormArrayName
directive instance.
method removeFormGroup
removeFormGroup: (dir: FormGroupName) => void;
Performs the necessary cleanup when a
FormGroupName
directive instance is removed from the view.Parameter dir
The
FormGroupName
directive instance.
method resetForm
resetForm: (value?: any) => void;
Resets the form to an initial value and resets its submitted status.
Parameter value
The new value for the form.
method updateModel
updateModel: (dir: FormControlName, value: any) => void;
Sets the new value for the provided
FormControlName
directive.Parameter dir
The
FormControlName
directive instance.Parameter value
The new value for the directive's control.
class FormGroupName
class FormGroupName extends AbstractFormGroupDirective implements OnInit, OnDestroy {}
Syncs a nested
FormGroup
orFormRecord
to a DOM element.This directive can only be used with a parent
FormGroupDirective
.It accepts the string name of the nested
FormGroup
orFormRecord
to link, and looks for aFormGroup
orFormRecord
registered with that name in the parentFormGroup
instance you passed intoFormGroupDirective
.Use nested form groups to validate a sub-group of a form separately from the rest or to group the values of certain controls into their own nested object.
See Also
[Reactive Forms Guide](guide/forms/reactive-forms)
### Access the group by name
The following example uses the
AbstractControl.get
method to access the associatedFormGroup
this.form.get('name');### Access individual controls in the group
The following example uses the
AbstractControl.get
method to access individual controls within the group using dot syntax.this.form.get('name.first');### Register a nested
FormGroup
.The following example registers a nested *name*
FormGroup
within an existingFormGroup
, and provides methods to retrieve the nestedFormGroup
and individual controls.ReactiveFormsModule
constructor
constructor( parent: ControlContainer, validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[]);
property name
name: string | number;
Tracks the name of the
FormGroup
bound to the directive. The name corresponds to a key in the parentFormGroup
orFormArray
. Accepts a name as a string or a number. The name in the form of a string is useful for individual forms, while the numerical form allows for form groups to be bound to indices when iterating over groups in aFormArray
.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< FormGroupName, '[formGroupName]', never, { name: { alias: 'formGroupName'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< FormGroupName, [ { optional: true; host: true; skipSelf: true }, { optional: true; self: true }, { optional: true; self: true } ]>;
class InternalFormsSharedModule
class ɵInternalFormsSharedModule {}
Internal module used for sharing directives between FormsModule and ReactiveFormsModule
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<ɵInternalFormsSharedModule, never>;
property ɵinj
static ɵinj: i0.ɵɵInjectorDeclaration<ɵInternalFormsSharedModule>;
property ɵmod
static ɵmod: i0.ɵɵNgModuleDeclaration< ɵInternalFormsSharedModule, [ typeof ɵNgNoValidate, typeof NgSelectOption, typeof ɵNgSelectMultipleOption, typeof DefaultValueAccessor, typeof NumberValueAccessor, typeof RangeValueAccessor, typeof CheckboxControlValueAccessor, typeof SelectControlValueAccessor, typeof SelectMultipleControlValueAccessor, typeof RadioControlValueAccessor, typeof NgControlStatus, typeof NgControlStatusGroup, typeof RequiredValidator, typeof MinLengthValidator, typeof MaxLengthValidator, typeof PatternValidator, typeof CheckboxRequiredValidator, typeof EmailValidator, typeof MinValidator, typeof MaxValidator ], never, [ typeof ɵNgNoValidate, typeof NgSelectOption, typeof ɵNgSelectMultipleOption, typeof DefaultValueAccessor, typeof NumberValueAccessor, typeof RangeValueAccessor, typeof CheckboxControlValueAccessor, typeof SelectControlValueAccessor, typeof SelectMultipleControlValueAccessor, typeof RadioControlValueAccessor, typeof NgControlStatus, typeof NgControlStatusGroup, typeof RequiredValidator, typeof MinLengthValidator, typeof MaxLengthValidator, typeof PatternValidator, typeof CheckboxRequiredValidator, typeof EmailValidator, typeof MinValidator, typeof MaxValidator ]>;
class NgControl
abstract class NgControl extends AbstractControlDirective {}
A base class that all
FormControl
-based directives extend. It binds aFormControl
object to a DOM element.
property name
name: string | number;
The name for the control
property valueAccessor
valueAccessor: ControlValueAccessor;
The value accessor for the control
method viewToModelUpdate
abstract viewToModelUpdate: (newValue: any) => void;
The callback method to update the model from the view when requested
Parameter newValue
The new value for the view
class NgControlStatus
class NgControlStatus extends AbstractControlStatus {}
Directive automatically applied to Angular form controls that sets CSS classes based on control status.
### CSS classes applied
The following classes are applied as the properties become true:
* ng-valid * ng-invalid * ng-pending * ng-pristine * ng-dirty * ng-untouched * ng-touched
ReactiveFormsModule FormsModule
constructor
constructor(cd: NgControl);
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NgControlStatus, '[formControlName],[ngModel],[formControl]', never, {}, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<NgControlStatus, [{ self: true }]>;
class NgControlStatusGroup
class NgControlStatusGroup extends AbstractControlStatus {}
Directive automatically applied to Angular form groups that sets CSS classes based on control status (valid/invalid/dirty/etc). On groups, this includes the additional class ng-submitted.
See Also
ReactiveFormsModule FormsModule
constructor
constructor(cd: ControlContainer);
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NgControlStatusGroup, '[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]', never, {}, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< NgControlStatusGroup, [{ optional: true; self: true }]>;
class NgForm
class NgForm extends ControlContainer implements Form, AfterViewInit {}
Creates a top-level
FormGroup
instance and binds it to a form to track aggregate form value and validation status.As soon as you import the
FormsModule
, this directive becomes active by default on all<form>
tags. You don't need to add a special selector.You optionally export the directive into a local template variable using
ngForm
as the key (ex:#myForm="ngForm"
). This is optional, but useful. Many properties from the underlyingFormGroup
instance are duplicated on the directive itself, so a reference to it gives you access to the aggregate value and validity status of the form, as well as user interaction properties likedirty
andtouched
.To register child controls with the form, use
NgModel
with aname
attribute. You may useNgModelGroup
to create sub-groups within the form.If necessary, listen to the directive's
ngSubmit
event to be notified when the user has triggered a form submission. ThengSubmit
event emits the original form submission event.In template driven forms, all
<form>
tags are automatically tagged asNgForm
. To import theFormsModule
but skip its usage in some forms, for example, to use native HTML5 validation, add thengNoForm
and the<form>
tags won't create anNgForm
directive. In reactive forms, usingngNoForm
is unnecessary because the<form>
tags are inert. In that case, you would refrain from using theformGroup
directive.### Listening for form submission
The following example shows how to capture the form values from the "ngSubmit" event.
### Setting the update options
The following example shows you how to change the "updateOn" option from its default using ngFormOptions.
<form [ngFormOptions]="{updateOn: 'blur'}"><input name="one" ngModel> <!-- this ngModel will update on blur --></form>### Native DOM validation UI
In order to prevent the native DOM form validation UI from interfering with Angular's form validation, Angular automatically adds the
novalidate
attribute on any<form>
wheneverFormModule
orReactiveFormModule
are imported into the application. If you want to explicitly enable native DOM validation UI with Angular forms, you can add thengNativeValidate
attribute to the<form>
element:<form ngNativeValidate>...</form>FormsModule
constructor
constructor( validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[], callSetDisabledState?: SetDisabledStateOption);
property control
readonly control: FormGroup<any>;
The internal
FormGroup
instance.
property controls
readonly controls: { [key: string]: AbstractControl<any, any> };
Returns a map of the controls in this group.
property form
form: FormGroup<any>;
The
FormGroup
instance created for this form.
property formDirective
readonly formDirective: Form;
The directive instance.
property ngSubmit
ngSubmit: EventEmitter<any>;
Event emitter for the "ngSubmit" event
property options
options: { updateOn?: FormHooks };
Tracks options for the
NgForm
instance.**updateOn**: Sets the default
updateOn
value for all childNgModels
below it unless explicitly set by a childNgModel
usingngModelOptions
). Defaults to 'change'. Possible values:'change'
|'blur'
|'submit'
.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NgForm, 'form:not([ngNoForm]):not([formGroup]),ng-form,[ngForm]', ['ngForm'], { options: { alias: 'ngFormOptions'; required: false } }, { ngSubmit: 'ngSubmit' }, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< NgForm, [ { optional: true; self: true }, { optional: true; self: true }, { optional: true } ]>;
property path
readonly path: string[];
Returns an array representing the path to this group. Because this directive always lives at the top level of a form, it is always an empty array.
property submitted
readonly submitted: boolean;
Returns whether the form submission has been triggered.
method addControl
addControl: (dir: NgModel) => void;
Method that sets up the control directive in this group, re-calculates its value and validity, and adds the instance to the internal list of directives.
Parameter dir
The
NgModel
directive instance.
method addFormGroup
addFormGroup: (dir: NgModelGroup) => void;
Adds a new
NgModelGroup
directive instance to the form.Parameter dir
The
NgModelGroup
directive instance.
method getControl
getControl: (dir: NgModel) => FormControl;
Retrieves the
FormControl
instance from the providedNgModel
directive.Parameter dir
The
NgModel
directive instance.
method getFormGroup
getFormGroup: (dir: NgModelGroup) => FormGroup;
Retrieves the
FormGroup
for a providedNgModelGroup
directive instanceParameter dir
The
NgModelGroup
directive instance.
method ngAfterViewInit
ngAfterViewInit: () => void;
method onReset
onReset: () => void;
Method called when the "reset" event is triggered on the form.
method onSubmit
onSubmit: ($event: Event) => boolean;
Method called when the "submit" event is triggered on the form. Triggers the
ngSubmit
emitter to emit the "submit" event as its payload.Parameter $event
The "submit" event object
method removeControl
removeControl: (dir: NgModel) => void;
Removes the
NgModel
instance from the internal list of directivesParameter dir
The
NgModel
directive instance.
method removeFormGroup
removeFormGroup: (dir: NgModelGroup) => void;
Removes the
NgModelGroup
directive instance from the form.Parameter dir
The
NgModelGroup
directive instance.
method resetForm
resetForm: (value?: any) => void;
Resets the form to an initial value and resets its submitted status.
Parameter value
The new value for the form.
method setValue
setValue: (value: { [key: string]: any }) => void;
Sets the value for this
FormGroup
.Parameter value
The new value
method updateModel
updateModel: (dir: NgControl, value: any) => void;
Sets the new value for the provided
NgControl
directive.Parameter dir
The
NgControl
directive instance.Parameter value
The new value for the directive's control.
class NgModel
class NgModel extends NgControl implements OnChanges, OnDestroy {}
Creates a
FormControl
instance from a [domain model](https://en.wikipedia.org/wiki/Domain_model) and binds it to a form control element.The
FormControl
instance tracks the value, user interaction, and validation status of the control and keeps the view synced with the model. If used within a parent form, the directive also registers itself with the form as a child control.This directive is used by itself or as part of a larger form. Use the
ngModel
selector to activate it.It accepts a domain model as an optional
Input
. If you have a one-way binding tongModel
with[]
syntax, changing the domain model's value in the component class sets the value in the view. If you have a two-way binding with[()]
syntax (also known as 'banana-in-a-box syntax'), the value in the UI always syncs back to the domain model in your class.To inspect the properties of the associated
FormControl
(like the validity state), export the directive into a local template variable usingngModel
as the key (ex:#myVar="ngModel"
). You can then access the control using the directive'scontrol
property. However, the most commonly used properties (likevalid
anddirty
) also exist on the control for direct access. See a full list of properties directly available inAbstractControlDirective
.See Also
### Using ngModel on a standalone control
The following examples show a simple standalone control using
ngModel
:When using the
ngModel
within<form>
tags, you'll also need to supply aname
attribute so that the control can be registered with the parent form under that name.In the context of a parent form, it's often unnecessary to include one-way or two-way binding, as the parent form syncs the value for you. You access its properties by exporting it into a local template variable using
ngForm
such as (#f="ngForm"
). Use the variable where needed on form submission.If you do need to populate initial values into your form, using a one-way binding for
ngModel
tends to be sufficient as long as you use the exported form's value rather than the domain model's value on submit.### Using ngModel within a form
The following example shows controls using
ngModel
within a form:### Using a standalone ngModel within a group
The following example shows you how to use a standalone ngModel control within a form. This controls the display of the form, but doesn't contain form data.
<form><input name="login" ngModel placeholder="Login"><input type="checkbox" ngModel [ngModelOptions]="{standalone: true}"> Show more options?</form><!-- form value: {login: ''} -->### Setting the ngModel
name
attribute through optionsThe following example shows you an alternate way to set the name attribute. Here, an attribute identified as name is used within a custom form control component. To still be able to specify the NgModel's name, you must specify it using the
ngModelOptions
input instead.<form><my-custom-form-control name="Nancy" ngModel [ngModelOptions]="{name: 'user'}"></my-custom-form-control></form><!-- form value: {user: ''} -->FormsModule
constructor
constructor( parent: ControlContainer, validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[], valueAccessors: ControlValueAccessor[], _changeDetectorRef?: any, callSetDisabledState?: SetDisabledStateOption);
property control
readonly control: FormControl<any>;
property formDirective
readonly formDirective: any;
The top-level directive for this control if present, otherwise null.
property isDisabled
isDisabled: boolean;
Tracks whether the control is disabled.
property model
model: any;
Tracks the value bound to this directive.
property name
name: string;
Tracks the name bound to the directive. If a parent form exists, it uses this name as a key to retrieve this control's value.
property ngAcceptInputType_isDisabled
static ngAcceptInputType_isDisabled: string | boolean;
property options
options: { name?: string; standalone?: boolean; updateOn?: FormHooks };
Tracks the configuration options for this
ngModel
instance.**name**: An alternative to setting the name attribute on the form control element. See the [example](api/forms/NgModel#using-ngmodel-on-a-standalone-control) for using
NgModel
as a standalone control.**standalone**: When set to true, the
ngModel
will not register itself with its parent form, and acts as if it's not in the form. Defaults to false. If no parent form exists, this option has no effect.**updateOn**: Defines the event upon which the form control value and validity update. Defaults to 'change'. Possible values:
'change'
|'blur'
|'submit'
.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NgModel, '[ngModel]:not([formControlName]):not([formControl])', ['ngModel'], { name: { alias: 'name'; required: false }; isDisabled: { alias: 'disabled'; required: false }; model: { alias: 'ngModel'; required: false }; options: { alias: 'ngModelOptions'; required: false }; }, { update: 'ngModelChange' }, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< NgModel, [ { optional: true; host: true }, { optional: true; self: true }, { optional: true; self: true }, { optional: true; self: true }, { optional: true }, { optional: true } ]>;
property path
readonly path: string[];
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.
property update
update: EventEmitter<any>;
Event emitter for producing the
ngModelChange
event after the view model updates.
property viewModel
viewModel: any;
Internal reference to the view model value.
method ngOnChanges
ngOnChanges: (changes: SimpleChanges) => void;
method ngOnDestroy
ngOnDestroy: () => void;
method viewToModelUpdate
viewToModelUpdate: (newValue: any) => void;
Sets the new value for the view model and emits an
ngModelChange
event.Parameter newValue
The new value emitted by
ngModelChange
.
class NgModelGroup
class NgModelGroup extends AbstractFormGroupDirective implements OnInit, OnDestroy {}
Creates and binds a
FormGroup
instance to a DOM element.This directive can only be used as a child of
NgForm
(within<form>
tags).Use this directive to validate a sub-group of your form separately from the rest of your form, or if some values in your domain model make more sense to consume together in a nested object.
Provide a name for the sub-group and it will become the key for the sub-group in the form's full value. If you need direct access, export the directive into a local template variable using
ngModelGroup
(ex:#myGroup="ngModelGroup"
).### Consuming controls in a grouping
The following example shows you how to combine controls together in a sub-group of the form.
FormsModule
constructor
constructor( parent: ControlContainer, validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[]);
property name
name: string;
Tracks the name of the
NgModelGroup
bound to the directive. The name corresponds to a key in the parentNgForm
.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NgModelGroup, '[ngModelGroup]', ['ngModelGroup'], { name: { alias: 'ngModelGroup'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< NgModelGroup, [ { host: true; skipSelf: true }, { optional: true; self: true }, { optional: true; self: true } ]>;
class NgSelectMultipleOption
class ɵNgSelectMultipleOption implements OnDestroy {}
Marks
<option>
as dynamic, so Angular can be notified when options change.See Also
SelectMultipleControlValueAccessor
ReactiveFormsModule FormsModule
constructor
constructor( _element: ElementRef, _renderer: Renderer2, _select: SelectMultipleControlValueAccessor);
property id
id: string;
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< ɵNgSelectMultipleOption, 'option', never, { ngValue: { alias: 'ngValue'; required: false }; value: { alias: 'value'; required: false }; }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< ɵNgSelectMultipleOption, [null, null, { optional: true; host: true }]>;
method ngOnDestroy
ngOnDestroy: () => void;
class NgSelectOption
class NgSelectOption implements OnDestroy {}
Marks
<option>
as dynamic, so Angular can be notified when options change.See Also
ReactiveFormsModule FormsModule
constructor
constructor( _element: ElementRef, _renderer: Renderer2, _select: SelectControlValueAccessor);
property id
id: string;
ID of the option element
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NgSelectOption, 'option', never, { ngValue: { alias: 'ngValue'; required: false }; value: { alias: 'value'; required: false }; }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< NgSelectOption, [null, null, { optional: true; host: true }]>;
method ngOnDestroy
ngOnDestroy: () => void;
class NumberValueAccessor
class NumberValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor {}
The
ControlValueAccessor
for writing a number value and listening to number input changes. The value accessor is used by theFormControlDirective
,FormControlName
, andNgModel
directives.### Using a number input with a reactive form.
The following example shows how to use a number input with a reactive form.
const totalCountControl = new FormControl();<input type="number" [formControl]="totalCountControl">ReactiveFormsModule FormsModule
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NumberValueAccessor, 'input[type=number][formControlName],input[type=number][formControl],input[type=number][ngModel]', never, {}, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<NumberValueAccessor, never>;
method registerOnChange
registerOnChange: (fn: (_: number | null) => void) => void;
Registers a function called when the control value changes.
method writeValue
writeValue: (value: number) => void;
Sets the "value" property on the input element.
class ɵInternalFormsSharedModule
class ɵInternalFormsSharedModule {}
Internal module used for sharing directives between FormsModule and ReactiveFormsModule
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<ɵInternalFormsSharedModule, never>;
property ɵinj
static ɵinj: i0.ɵɵInjectorDeclaration<ɵInternalFormsSharedModule>;
property ɵmod
static ɵmod: i0.ɵɵNgModuleDeclaration< ɵInternalFormsSharedModule, [ typeof ɵNgNoValidate, typeof NgSelectOption, typeof ɵNgSelectMultipleOption, typeof DefaultValueAccessor, typeof NumberValueAccessor, typeof RangeValueAccessor, typeof CheckboxControlValueAccessor, typeof SelectControlValueAccessor, typeof SelectMultipleControlValueAccessor, typeof RadioControlValueAccessor, typeof NgControlStatus, typeof NgControlStatusGroup, typeof RequiredValidator, typeof MinLengthValidator, typeof MaxLengthValidator, typeof PatternValidator, typeof CheckboxRequiredValidator, typeof EmailValidator, typeof MinValidator, typeof MaxValidator ], never, [ typeof ɵNgNoValidate, typeof NgSelectOption, typeof ɵNgSelectMultipleOption, typeof DefaultValueAccessor, typeof NumberValueAccessor, typeof RangeValueAccessor, typeof CheckboxControlValueAccessor, typeof SelectControlValueAccessor, typeof SelectMultipleControlValueAccessor, typeof RadioControlValueAccessor, typeof NgControlStatus, typeof NgControlStatusGroup, typeof RequiredValidator, typeof MinLengthValidator, typeof MaxLengthValidator, typeof PatternValidator, typeof CheckboxRequiredValidator, typeof EmailValidator, typeof MinValidator, typeof MaxValidator ]>;
class RadioControlValueAccessor
class RadioControlValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor, OnDestroy, OnInit {}
The
ControlValueAccessor
for writing radio control values and listening to radio control changes. The value accessor is used by theFormControlDirective
,FormControlName
, andNgModel
directives.### Using radio buttons with reactive form directives
The follow example shows how to use radio buttons in a reactive form. When using radio buttons in a reactive form, radio buttons in the same group should have the same
formControlName
. Providing aname
attribute is optional.ReactiveFormsModule FormsModule
constructor
constructor( renderer: Renderer2, elementRef: ElementRef, _registry: RadioControlRegistry, _injector: Injector);
property formControlName
formControlName: string;
Tracks the name of the
FormControl
bound to the directive. The name corresponds to a key in the parentFormGroup
orFormArray
.
property name
name: string;
Tracks the name of the radio input element.
property onChange
onChange: () => void;
The registered callback function called when a change event occurs on the input element. Note: we declare
onChange
here (also used as host listener) as a function with no arguments to override theonChange
function (which expects 1 argument) in the parentBaseControlValueAccessor
class.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< RadioControlValueAccessor, 'input[type=radio][formControlName],input[type=radio][formControl],input[type=radio][ngModel]', never, { name: { alias: 'name'; required: false }; formControlName: { alias: 'formControlName'; required: false }; value: { alias: 'value'; required: false }; }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<RadioControlValueAccessor, never>;
property value
value: any;
Tracks the value of the radio input element
method fireUncheck
fireUncheck: (value: any) => void;
Sets the "value" on the radio input element and unchecks it.
Parameter value
method ngOnDestroy
ngOnDestroy: () => void;
method ngOnInit
ngOnInit: () => void;
method registerOnChange
registerOnChange: (fn: (_: any) => {}) => void;
Registers a function called when the control value changes.
method setDisabledState
setDisabledState: (isDisabled: boolean) => void;
method writeValue
writeValue: (value: any) => void;
Sets the "checked" property value on the radio input element.
class RangeValueAccessor
class RangeValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor {}
The
ControlValueAccessor
for writing a range value and listening to range input changes. The value accessor is used by theFormControlDirective
,FormControlName
, andNgModel
directives.### Using a range input with a reactive form
The following example shows how to use a range input with a reactive form.
const ageControl = new FormControl();<input type="range" [formControl]="ageControl">ReactiveFormsModule FormsModule
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< RangeValueAccessor, 'input[type=range][formControlName],input[type=range][formControl],input[type=range][ngModel]', never, {}, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<RangeValueAccessor, never>;
method registerOnChange
registerOnChange: (fn: (_: number | null) => void) => void;
Registers a function called when the control value changes.
method writeValue
writeValue: (value: any) => void;
Sets the "value" property on the input element.
class SelectControlValueAccessor
class SelectControlValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor {}
The
ControlValueAccessor
for writing select control values and listening to select control changes. The value accessor is used by theFormControlDirective
,FormControlName
, andNgModel
directives.### Using select controls in a reactive form
The following examples show how to use a select control in a reactive form.
### Using select controls in a template-driven form
To use a select in a template-driven form, simply add an
ngModel
and aname
attribute to the main<select>
tag.### Customizing option selection
Angular uses object identity to select option. It's possible for the identities of items to change while the data does not. This can happen, for example, if the items are produced from an RPC to the server, and that RPC is re-run. Even if the data hasn't changed, the second response will produce objects with different identities.
To customize the default option comparison algorithm,
<select>
supportscompareWith
input.compareWith
takes a **function** which has two arguments:option1
andoption2
. IfcompareWith
is given, Angular selects option by the return value of the function.const selectedCountriesControl = new FormControl();<select [compareWith]="compareFn" [formControl]="selectedCountriesControl"><option *ngFor="let country of countries" [ngValue]="country">{{country.name}}</option></select>compareFn(c1: Country, c2: Country): boolean {return c1 && c2 ? c1.id === c2.id : c1 === c2;}**Note:** We listen to the 'change' event because 'input' events aren't fired for selects in IE, see: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event#browser_compatibility
ReactiveFormsModule FormsModule
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< SelectControlValueAccessor, 'select:not([multiple])[formControlName],select:not([multiple])[formControl],select:not([multiple])[ngModel]', never, { compareWith: { alias: 'compareWith'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<SelectControlValueAccessor, never>;
property value
value: any;
method registerOnChange
registerOnChange: (fn: (value: any) => any) => void;
Registers a function called when the control value changes.
method writeValue
writeValue: (value: any) => void;
Sets the "value" property on the select element.
class SelectMultipleControlValueAccessor
class SelectMultipleControlValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor {}
The
ControlValueAccessor
for writing multi-select control values and listening to multi-select control changes. The value accessor is used by theFormControlDirective
,FormControlName
, andNgModel
directives.See Also
### Using a multi-select control
The follow example shows you how to use a multi-select control with a reactive form.
const countryControl = new FormControl();<select multiple name="countries" [formControl]="countryControl"><option *ngFor="let country of countries" [ngValue]="country">{{ country.name }}</option></select>### Customizing option selection
To customize the default option comparison algorithm,
<select>
supportscompareWith
input. See theSelectControlValueAccessor
for usage.ReactiveFormsModule FormsModule
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< SelectMultipleControlValueAccessor, 'select[multiple][formControlName],select[multiple][formControl],select[multiple][ngModel]', never, { compareWith: { alias: 'compareWith'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<SelectMultipleControlValueAccessor, never>;
property value
value: any;
The current value.
method registerOnChange
registerOnChange: (fn: (value: any) => any) => void;
Registers a function called when the control value changes and writes an array of the selected options.
method writeValue
writeValue: (value: any) => void;
Sets the "value" property on one or of more of the select's options.
interface ControlValueAccessor
interface ControlValueAccessor {}
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 Also
method registerOnChange
registerOnChange: (fn: any) => void;
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.### Store the change function
The following example stores the provided function as an internal method.
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:
host: {'(change)': '_onChange($event.target.value)'}Parameter fn
The callback function to register
method registerOnTouched
registerOnTouched: (fn: any) => void;
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".### Store the callback function
The following example stores the provided function as an internal method.
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:
host: {'(blur)': '_onTouched()'}Parameter fn
The callback function to register
method setDisabledState
setDisabledState: (isDisabled: boolean) => void;
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.
The following is an example of writing the disabled property to a native DOM element:
setDisabledState(isDisabled: boolean): void {this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);}Parameter isDisabled
The disabled status to set on the element
method writeValue
writeValue: (obj: any) => void;
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.
### Write a value to the element
The following example writes a value to the native DOM element.
writeValue(value: any): void {this._renderer.setProperty(this._elementRef.nativeElement, 'value', value);}Parameter obj
The new value for the element
namespace i5
namespace i5 {}
class NumberValueAccessor
class NumberValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor {}
The
ControlValueAccessor
for writing a number value and listening to number input changes. The value accessor is used by theFormControlDirective
,FormControlName
, andNgModel
directives.### Using a number input with a reactive form.
The following example shows how to use a number input with a reactive form.
const totalCountControl = new FormControl();<input type="number" [formControl]="totalCountControl">ReactiveFormsModule FormsModule
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NumberValueAccessor, 'input[type=number][formControlName],input[type=number][formControl],input[type=number][ngModel]', never, {}, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<NumberValueAccessor, never>;
method registerOnChange
registerOnChange: (fn: (_: number | null) => void) => void;
Registers a function called when the control value changes.
method writeValue
writeValue: (value: number) => void;
Sets the "value" property on the input element.
namespace i5_2
namespace i5_2 {}
variable NG_MODEL_WITH_FORM_CONTROL_WARNING
const NG_MODEL_WITH_FORM_CONTROL_WARNING: InjectionToken<unknown>;
Token to provide to turn off the ngModel warning on formControl and formControlName.
class FormControlDirective
class FormControlDirective extends NgControl implements OnChanges, OnDestroy {}
Synchronizes a standalone
FormControl
instance to a form control element.Note that support for using the
ngModel
input property andngModelChange
event with reactive form directives was deprecated in Angular v6 and is scheduled for removal in a future version of Angular.See Also
[Reactive Forms Guide](guide/forms/reactive-forms)
The following example shows how to register a standalone control and set its value.
ReactiveFormsModule
constructor
constructor( validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[], valueAccessors: ControlValueAccessor[], _ngModelWarningConfig: string, callSetDisabledState?: SetDisabledStateOption);
property control
readonly control: FormControl<any>;
The
FormControl
bound to this directive.
property form
form: FormControl<any>;
Tracks the
FormControl
instance bound to the directive.
property model
model: any;
Deprecated
as of v6
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< FormControlDirective, '[formControl]', ['ngForm'], { form: { alias: 'formControl'; required: false }; isDisabled: { alias: 'disabled'; required: false }; model: { alias: 'ngModel'; required: false }; }, { update: 'ngModelChange' }, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< FormControlDirective, [ { optional: true; self: true }, { optional: true; self: true }, { optional: true; self: true }, { optional: true }, { optional: true } ]>;
property path
readonly path: string[];
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.
property update
update: EventEmitter<any>;
Deprecated
as of v6
property viewModel
viewModel: any;
Internal reference to the view model value.
method ngOnChanges
ngOnChanges: (changes: SimpleChanges) => void;
method ngOnDestroy
ngOnDestroy: () => void;
method viewToModelUpdate
viewToModelUpdate: (newValue: any) => void;
Sets the new value for the view model and emits an
ngModelChange
event.Parameter newValue
The new value for the view model.
namespace i6
namespace i6 {}
class RangeValueAccessor
class RangeValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor {}
The
ControlValueAccessor
for writing a range value and listening to range input changes. The value accessor is used by theFormControlDirective
,FormControlName
, andNgModel
directives.### Using a range input with a reactive form
The following example shows how to use a range input with a reactive form.
const ageControl = new FormControl();<input type="range" [formControl]="ageControl">ReactiveFormsModule FormsModule
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< RangeValueAccessor, 'input[type=range][formControlName],input[type=range][formControl],input[type=range][ngModel]', never, {}, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<RangeValueAccessor, never>;
method registerOnChange
registerOnChange: (fn: (_: number | null) => void) => void;
Registers a function called when the control value changes.
method writeValue
writeValue: (value: any) => void;
Sets the "value" property on the input element.
namespace i6_2
namespace i6_2 {}
class FormGroupDirective
class FormGroupDirective extends ControlContainer implements Form, OnChanges, OnDestroy {}
Binds an existing
FormGroup
orFormRecord
to a DOM element.This directive accepts an existing
FormGroup
instance. It will then use thisFormGroup
instance to match any childFormControl
,FormGroup
/FormRecord
, andFormArray
instances to childFormControlName
,FormGroupName
, andFormArrayName
directives.See Also
[Reactive Forms Guide](guide/forms/reactive-forms)
### Register Form Group
The following example registers a
FormGroup
with first name and last name controls, and listens for the *ngSubmit* event when the button is clicked.ReactiveFormsModule
constructor
constructor( validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[], callSetDisabledState?: SetDisabledStateOption);
property control
readonly control: FormGroup<any>;
Returns the
FormGroup
bound to this directive.
property directives
directives: FormControlName[];
Tracks the list of added
FormControlName
instances
property form
form: FormGroup<any>;
Tracks the
FormGroup
bound to this directive.
property formDirective
readonly formDirective: Form;
Returns this directive's instance.
property ngSubmit
ngSubmit: EventEmitter<any>;
Emits an event when the form submission has been triggered.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< FormGroupDirective, '[formGroup]', ['ngForm'], { form: { alias: 'formGroup'; required: false } }, { ngSubmit: 'ngSubmit' }, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< FormGroupDirective, [ { optional: true; self: true }, { optional: true; self: true }, { optional: true } ]>;
property path
readonly path: string[];
Returns an array representing the path to this group. Because this directive always lives at the top level of a form, it always an empty array.
property submitted
submitted: boolean;
Reports whether the form submission has been triggered.
method addControl
addControl: (dir: FormControlName) => FormControl;
Method that sets up the control directive in this group, re-calculates its value and validity, and adds the instance to the internal list of directives.
Parameter dir
The
FormControlName
directive instance.
method addFormArray
addFormArray: (dir: FormArrayName) => void;
Performs the necessary setup when a
FormArrayName
directive instance is added to the view.Parameter dir
The
FormArrayName
directive instance.
method addFormGroup
addFormGroup: (dir: FormGroupName) => void;
Adds a new
FormGroupName
directive instance to the form.Parameter dir
The
FormGroupName
directive instance.
method getControl
getControl: (dir: FormControlName) => FormControl;
Retrieves the
FormControl
instance from the providedFormControlName
directiveParameter dir
The
FormControlName
directive instance.
method getFormArray
getFormArray: (dir: FormArrayName) => FormArray;
Retrieves the
FormArray
for a providedFormArrayName
directive instance.Parameter dir
The
FormArrayName
directive instance.
method getFormGroup
getFormGroup: (dir: FormGroupName) => FormGroup;
Retrieves the
FormGroup
for a providedFormGroupName
directive instanceParameter dir
The
FormGroupName
directive instance.
method ngOnChanges
ngOnChanges: (changes: SimpleChanges) => void;
method ngOnDestroy
ngOnDestroy: () => void;
method onReset
onReset: () => void;
Method called when the "reset" event is triggered on the form.
method onSubmit
onSubmit: ($event: Event) => boolean;
Method called with the "submit" event is triggered on the form. Triggers the
ngSubmit
emitter to emit the "submit" event as its payload.Parameter $event
The "submit" event object
method removeControl
removeControl: (dir: FormControlName) => void;
Removes the
FormControlName
instance from the internal list of directivesParameter dir
The
FormControlName
directive instance.
method removeFormArray
removeFormArray: (dir: FormArrayName) => void;
Performs the necessary cleanup when a
FormArrayName
directive instance is removed from the view.Parameter dir
The
FormArrayName
directive instance.
method removeFormGroup
removeFormGroup: (dir: FormGroupName) => void;
Performs the necessary cleanup when a
FormGroupName
directive instance is removed from the view.Parameter dir
The
FormGroupName
directive instance.
method resetForm
resetForm: (value?: any) => void;
Resets the form to an initial value and resets its submitted status.
Parameter value
The new value for the form.
method updateModel
updateModel: (dir: FormControlName, value: any) => void;
Sets the new value for the provided
FormControlName
directive.Parameter dir
The
FormControlName
directive instance.Parameter value
The new value for the directive's control.
namespace i7
namespace i7 {}
class CheckboxControlValueAccessor
class CheckboxControlValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor {}
A
ControlValueAccessor
for writing a value and listening to changes on a checkbox input element.### Using a checkbox with a reactive form.
The following example shows how to use a checkbox with a reactive form.
const rememberLoginControl = new FormControl();<input type="checkbox" [formControl]="rememberLoginControl">ReactiveFormsModule FormsModule
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< CheckboxControlValueAccessor, 'input[type=checkbox][formControlName],input[type=checkbox][formControl],input[type=checkbox][ngModel]', never, {}, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<CheckboxControlValueAccessor, never>;
method writeValue
writeValue: (value: any) => void;
Sets the "checked" property on the input element.
namespace i7_2
namespace i7_2 {}
class FormControlName
class FormControlName extends NgControl implements OnChanges, OnDestroy {}
Syncs a
FormControl
in an existingFormGroup
to a form control element by name.See Also
[Reactive Forms Guide](guide/forms/reactive-forms)
### Register
FormControl
within a groupThe following example shows how to register multiple form controls within a form group and set their value.
To see
formControlName
examples with different form control types, see:* Radio buttons:
RadioControlValueAccessor
* Selects:SelectControlValueAccessor
### Use with ngModel is deprecated
Support for using the
ngModel
input property andngModelChange
event with reactive form directives has been deprecated in Angular v6 and is scheduled for removal in a future version of Angular.ReactiveFormsModule
constructor
constructor( parent: ControlContainer, validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[], valueAccessors: ControlValueAccessor[], _ngModelWarningConfig: string);
property control
readonly control: FormControl<any>;
Tracks the
FormControl
instance bound to the directive.
property formDirective
readonly formDirective: any;
The top-level directive for this group if present, otherwise null.
property model
model: any;
Deprecated
as of v6
property name
name: string | number;
Tracks the name of the
FormControl
bound to the directive. The name corresponds to a key in the parentFormGroup
orFormArray
. Accepts a name as a string or a number. The name in the form of a string is useful for individual forms, while the numerical form allows for form controls to be bound to indices when iterating over controls in aFormArray
.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< FormControlName, '[formControlName]', never, { name: { alias: 'formControlName'; required: false }; isDisabled: { alias: 'disabled'; required: false }; model: { alias: 'ngModel'; required: false }; }, { update: 'ngModelChange' }, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< FormControlName, [ { optional: true; host: true; skipSelf: true }, { optional: true; self: true }, { optional: true; self: true }, { optional: true; self: true }, { optional: true } ]>;
property path
readonly path: string[];
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.
property update
update: EventEmitter<any>;
Deprecated
as of v6
method ngOnChanges
ngOnChanges: (changes: SimpleChanges) => void;
method ngOnDestroy
ngOnDestroy: () => void;
method viewToModelUpdate
viewToModelUpdate: (newValue: any) => void;
Sets the new value for the view model and emits an
ngModelChange
event.Parameter newValue
The new value for the view model.
namespace i8
namespace i8 {}
class RadioControlRegistry
class RadioControlRegistry {}
Class used by Angular to track radio buttons. For internal use only.
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<RadioControlRegistry, never>;
property ɵprov
static ɵprov: i0.ɵɵInjectableDeclaration<RadioControlRegistry>;
method add
add: (control: NgControl, accessor: RadioControlValueAccessor) => void;
Adds a control to the internal registry. For internal use only.
method remove
remove: (accessor: RadioControlValueAccessor) => void;
Removes a control from the internal registry. For internal use only.
method select
select: (accessor: RadioControlValueAccessor) => void;
Selects a radio button. For internal use only.
class RadioControlValueAccessor
class RadioControlValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor, OnDestroy, OnInit {}
The
ControlValueAccessor
for writing radio control values and listening to radio control changes. The value accessor is used by theFormControlDirective
,FormControlName
, andNgModel
directives.### Using radio buttons with reactive form directives
The follow example shows how to use radio buttons in a reactive form. When using radio buttons in a reactive form, radio buttons in the same group should have the same
formControlName
. Providing aname
attribute is optional.ReactiveFormsModule FormsModule
constructor
constructor( renderer: Renderer2, elementRef: ElementRef, _registry: RadioControlRegistry, _injector: Injector);
property formControlName
formControlName: string;
Tracks the name of the
FormControl
bound to the directive. The name corresponds to a key in the parentFormGroup
orFormArray
.
property name
name: string;
Tracks the name of the radio input element.
property onChange
onChange: () => void;
The registered callback function called when a change event occurs on the input element. Note: we declare
onChange
here (also used as host listener) as a function with no arguments to override theonChange
function (which expects 1 argument) in the parentBaseControlValueAccessor
class.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< RadioControlValueAccessor, 'input[type=radio][formControlName],input[type=radio][formControl],input[type=radio][ngModel]', never, { name: { alias: 'name'; required: false }; formControlName: { alias: 'formControlName'; required: false }; value: { alias: 'value'; required: false }; }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<RadioControlValueAccessor, never>;
property value
value: any;
Tracks the value of the radio input element
method fireUncheck
fireUncheck: (value: any) => void;
Sets the "value" on the radio input element and unchecks it.
Parameter value
method ngOnDestroy
ngOnDestroy: () => void;
method ngOnInit
ngOnInit: () => void;
method registerOnChange
registerOnChange: (fn: (_: any) => {}) => void;
Registers a function called when the control value changes.
method setDisabledState
setDisabledState: (isDisabled: boolean) => void;
method writeValue
writeValue: (value: any) => void;
Sets the "checked" property value on the radio input element.
namespace i8_2
namespace i8_2 {}
variable formArrayNameProvider
const formArrayNameProvider: any;
class FormArrayName
class FormArrayName extends ControlContainer implements OnInit, OnDestroy {}
Syncs a nested
FormArray
to a DOM element.This directive is designed to be used with a parent
FormGroupDirective
(selector:[formGroup]
).It accepts the string name of the nested
FormArray
you want to link, and will look for aFormArray
registered with that name in the parentFormGroup
instance you passed intoFormGroupDirective
.See Also
[Reactive Forms Guide](guide/forms/reactive-forms)
### Example
ReactiveFormsModule
constructor
constructor( parent: ControlContainer, validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[]);
property control
readonly control: FormArray<any>;
The
FormArray
bound to this directive.
property formDirective
readonly formDirective: FormGroupDirective;
The top-level directive for this group if present, otherwise null.
property name
name: string | number;
Tracks the name of the
FormArray
bound to the directive. The name corresponds to a key in the parentFormGroup
orFormArray
. Accepts a name as a string or a number. The name in the form of a string is useful for individual forms, while the numerical form allows for form arrays to be bound to indices when iterating over arrays in aFormArray
.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< FormArrayName, '[formArrayName]', never, { name: { alias: 'formArrayName'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< FormArrayName, [ { optional: true; host: true; skipSelf: true }, { optional: true; self: true }, { optional: true; self: true } ]>;
property path
readonly path: string[];
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.
method ngOnDestroy
ngOnDestroy: () => void;
A lifecycle method called before the directive's instance is destroyed. For internal use only.
method ngOnInit
ngOnInit: () => void;
A lifecycle method called when the directive's inputs are initialized. For internal use only.
Throws
If the directive does not have a valid parent.
class FormGroupName
class FormGroupName extends AbstractFormGroupDirective implements OnInit, OnDestroy {}
Syncs a nested
FormGroup
orFormRecord
to a DOM element.This directive can only be used with a parent
FormGroupDirective
.It accepts the string name of the nested
FormGroup
orFormRecord
to link, and looks for aFormGroup
orFormRecord
registered with that name in the parentFormGroup
instance you passed intoFormGroupDirective
.Use nested form groups to validate a sub-group of a form separately from the rest or to group the values of certain controls into their own nested object.
See Also
[Reactive Forms Guide](guide/forms/reactive-forms)
### Access the group by name
The following example uses the
AbstractControl.get
method to access the associatedFormGroup
this.form.get('name');### Access individual controls in the group
The following example uses the
AbstractControl.get
method to access individual controls within the group using dot syntax.this.form.get('name.first');### Register a nested
FormGroup
.The following example registers a nested *name*
FormGroup
within an existingFormGroup
, and provides methods to retrieve the nestedFormGroup
and individual controls.ReactiveFormsModule
constructor
constructor( parent: ControlContainer, validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[]);
property name
name: string | number;
Tracks the name of the
FormGroup
bound to the directive. The name corresponds to a key in the parentFormGroup
orFormArray
. Accepts a name as a string or a number. The name in the form of a string is useful for individual forms, while the numerical form allows for form groups to be bound to indices when iterating over groups in aFormArray
.
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< FormGroupName, '[formGroupName]', never, { name: { alias: 'formGroupName'; required: false } }, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< FormGroupName, [ { optional: true; host: true; skipSelf: true }, { optional: true; self: true }, { optional: true; self: true } ]>;
namespace i9
namespace i9 {}
variable ngControlStatusHost
const ngControlStatusHost: { '[class.ng-untouched]': string; '[class.ng-touched]': string; '[class.ng-pristine]': string; '[class.ng-dirty]': string; '[class.ng-valid]': string; '[class.ng-invalid]': string; '[class.ng-pending]': string;};
variable ngGroupStatusHost
const ngGroupStatusHost: { '[class.ng-submitted]': string; '[class.ng-untouched]': string; '[class.ng-touched]': string; '[class.ng-pristine]': string; '[class.ng-dirty]': string; '[class.ng-valid]': string; '[class.ng-invalid]': string; '[class.ng-pending]': string;};
class AbstractControlStatus
class AbstractControlStatus {}
constructor
constructor(cd: AbstractControlDirective);
property isDirty
readonly isDirty: boolean;
property isInvalid
readonly isInvalid: boolean;
property isPending
readonly isPending: boolean;
property isPristine
readonly isPristine: boolean;
property isSubmitted
readonly isSubmitted: boolean;
property isTouched
readonly isTouched: boolean;
property isUntouched
readonly isUntouched: boolean;
property isValid
readonly isValid: boolean;
class NgControlStatus
class NgControlStatus extends AbstractControlStatus {}
Directive automatically applied to Angular form controls that sets CSS classes based on control status.
### CSS classes applied
The following classes are applied as the properties become true:
* ng-valid * ng-invalid * ng-pending * ng-pristine * ng-dirty * ng-untouched * ng-touched
ReactiveFormsModule FormsModule
constructor
constructor(cd: NgControl);
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NgControlStatus, '[formControlName],[ngModel],[formControl]', never, {}, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<NgControlStatus, [{ self: true }]>;
class NgControlStatusGroup
class NgControlStatusGroup extends AbstractControlStatus {}
Directive automatically applied to Angular form groups that sets CSS classes based on control status (valid/invalid/dirty/etc). On groups, this includes the additional class ng-submitted.
See Also
ReactiveFormsModule FormsModule
constructor
constructor(cd: ControlContainer);
property ɵdir
static ɵdir: i0.ɵɵDirectiveDeclaration< NgControlStatusGroup, '[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]', never, {}, {}, never, never, false, never>;
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< NgControlStatusGroup, [{ optional: true; self: true }]>;
Package Files (1)
Dependencies (1)
Dev Dependencies (0)
No dev dependencies.
Peer Dependencies (4)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@angular/forms
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@angular/forms)
- HTML<a href="https://www.jsdocs.io/package/@angular/forms"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 13403 ms. - Missing or incorrect documentation? Open an issue for this package.