class
final
Tracks the value and validity state of a group of FormControl
instances.
class FormGroup<TControl extends { [K in keyof TControl]: AbstractControl<any>; } = any> extends AbstractControl<ɵTypedOrUntyped<TControl, ɵFormGroupValue<TControl>, any>, ɵTypedOrUntyped<TControl, ɵFormGroupRawValue<TControl>, any>> { constructor(controls: TControl, validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]) controls: ɵTypedOrUntyped<TControl, TControl, {...} registerControl<K extends string & keyof TControl>(name: K, control: TControl[K]): TControl[K] addControl<K extends string & keyof TControl>(name: K, control: Required<TControl>[K], options: { emitEvent?: boolean; } = {}): void removeControl(name: string, options: { emitEvent?: boolean; } = {}): void setControl<K extends string & keyof TControl>(name: K, control: TControl[K], options: { emitEvent?: boolean; } = {}): void contains<K extends string & keyof TControl>(controlName: K): boolean setValue(value: ɵIsAny<TControl, { [key: string]: any; }, { [K in keyof TControl]: ɵRawValue<TControl[K]>; }>, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void patchValue(value: ɵIsAny<TControl, { [key: string]: any; }, Partial<{ [K in keyof TControl]: ɵValue<TControl[K]>; }>>, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void reset(value: ɵIsAny<TControl, any, ɵIsAny<TControl, { [key: string]: any; }, Partial<{ [K in keyof TControl]: ɵValue<TControl[K]>; }>>> = {} as unknown as ɵFormGroupValue<TControl>, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void getRawValue(): ɵTypedOrUntyped<TControl, ɵFormGroupRawValue<TControl>, any> // inherited from forms/AbstractControl constructor(validators: ValidatorFn | ValidatorFn[], asyncValidators: AsyncValidatorFn | AsyncValidatorFn[]) value: TValue validator: ValidatorFn | null asyncValidator: AsyncValidatorFn | null parent: FormGroup | FormArray | null status: FormControlStatus valid: boolean invalid: boolean pending: boolean disabled: boolean enabled: boolean errors: ValidationErrors | null pristine: boolean dirty: boolean touched: boolean untouched: boolean valueChanges: Observable<TValue> statusChanges: Observable<FormControlStatus> updateOn: FormHooks root: AbstractControl setValidators(validators: ValidatorFn | ValidatorFn[]): void setAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void addValidators(validators: ValidatorFn | ValidatorFn[]): void addAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void removeValidators(validators: ValidatorFn | ValidatorFn[]): void removeAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void hasValidator(validator: ValidatorFn): boolean hasAsyncValidator(validator: AsyncValidatorFn): boolean clearValidators(): void clearAsyncValidators(): void markAsTouched(opts: { onlySelf?: boolean; } = {}): void markAllAsTouched(): void markAsUntouched(opts: { onlySelf?: boolean; } = {}): void markAsDirty(opts: { onlySelf?: boolean; } = {}): void markAsPristine(opts: { onlySelf?: boolean; } = {}): void markAsPending(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void disable(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void enable(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void setParent(parent: FormGroup<any> | FormArray<any>): void abstract setValue(value: TRawValue, options?: Object): void abstract patchValue(value: TValue, options?: Object): void abstract reset(value?: TValue, options?: Object): void getRawValue(): any updateValueAndValidity(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void setErrors(errors: ValidationErrors, opts: { emitEvent?: boolean; } = {}): void get<P extends string | ((string | number)[])>(path: P): AbstractControl<ɵGetProperty<TRawValue, P>> | null getError(errorCode: string, path?: string | (string | number)[]): any hasError(errorCode: string, path?: string | (string | number)[]): boolean }
A FormGroup
aggregates the values of each child FormControl
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 with FormControl
, FormArray
, and FormRecord
.
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 parameter TControl
, which is an object type with inner control types as values.
Further information is available in the Usage Notes...
Creates a new | |||||||||
|
controls | TControl | A collection of child controls. The key for each child is the name under which it is registered. |
validatorOrOpts | ValidatorFn | AbstractControlOptions | ValidatorFn[] | A synchronous validator function, or an array of such functions, or an Optional. Default is |
asyncValidator | AsyncValidatorFn | AsyncValidatorFn[] | A single async validator or array of async validator functions Optional. Default is |
Property | Description |
---|---|
controls: ɵTypedOrUntyped<TControl, TControl, {
[key: string]: AbstractControl<any>;
}> |
registerControl() | ||||||
---|---|---|---|---|---|---|
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). |
name | K | The control name to register in the collection |
control | TControl[K] | Provides the control for the given name |
TControl[K]
registerControl(name: string, control: AbstractControl<any, any>): AbstractControl<any>
name | string | |
control | AbstractControl<any, any> |
AbstractControl<any>
This method does not update the value or validity of the control. Use FormGroup#addControl
instead.
addControl() | |||||||||
---|---|---|---|---|---|---|---|---|---|
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). |
name | string | The control name to add to the collection |
control | AbstractControl<any, any> | Provides the control for the given name |
options | object | Specifies whether this FormGroup instance should emit events after a new control is added.
Optional. Default is |
void
addControl<K extends string & keyof TControl>(name: K, control: Required<TControl>[K], options?: { emitEvent?: boolean; }): void
name | K | |
control | Required<TControl>[K] | |
options | object | Optional. Default is |
void
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 FormGroup#setControl
method instead. This method also updates the value and validity of the control.
removeControl() | ||||||
---|---|---|---|---|---|---|
Remove a control from this group. In a strongly-typed group, required controls cannot be removed. | ||||||
|
name | string | |
options | object | Optional. Default is |
void
removeControl<S extends string>(name: ɵOptionalKeys<TControl> & S, options?: { emitEvent?: boolean; }): void
name | ɵOptionalKeys<TControl> & S | |
options | object | Optional. Default is |
void
This method also updates the value and validity of the control.
setControl() | |||||||||
---|---|---|---|---|---|---|---|---|---|
Replace an existing control. In a strongly-typed group, the control must be in the group's type (possibly as an optional key). |
name | K | The control name to replace in the collection |
control | TControl[K] | Provides the control for the given name |
options | object | Specifies whether this FormGroup instance should emit events after an existing control is replaced.
Optional. Default is |
void
setControl(name: string, control: AbstractControl<any, any>, options?: { emitEvent?: boolean; }): void
name | string | |
control | AbstractControl<any, any> | |
options | object | Optional. Default is |
void
If a control with a given name does not exist in this FormGroup
, it will be added.
contains() | |||
---|---|---|---|
Check whether there is an enabled control with the given name in the group. |
controlName | K | The control name to check for existence in the collection |
boolean
: false for disabled controls, true otherwise.
contains(controlName: string): boolean
controlName | string |
boolean
Reports false for disabled controls. If you'd like to check for existence in the group only, use AbstractControl#get
instead.
setValue() | ||||||
---|---|---|---|---|---|---|
Sets the value of the | ||||||
|
value | ɵIsAny<TControl, { [key: string]: any; }, { [K in keyof TControl]: ɵRawValue<TControl[K]>; }> | The new value for the control that matches the structure of the group. |
options | object | Configuration options that determine how the control propagates changes and emits events after the value changes. The configuration options are passed to the
Optional. Default is |
void
Error
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.
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'}
patchValue() | ||||||
---|---|---|---|---|---|---|
Patches the value of the | ||||||
|
value | ɵIsAny<TControl, { [key: string]: any; }, Partial<{ [K in keyof TControl]: ɵValue<TControl[K]>; }>> | The object that matches the structure of the group. |
options | object | Configuration options that determine how the control propagates changes and emits events after the value is patched.
Optional. Default is |
void
It accepts both super-sets and sub-sets of the group without throwing an error.
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}
reset() | ||||||
---|---|---|---|---|---|---|
Resets the | ||||||
|
value | ɵIsAny<TControl, any, ɵIsAny<TControl, { [key: string]: any; }, Partial<{ [K in keyof TControl]: ɵValue<TControl[K]>; }>>> | Resets the control with an initial value, or an object that defines the initial value and disabled state. Optional. Default is |
options | object | Configuration options that determine how the control propagates changes and emits events when the group is reset.
Optional. Default is |
void
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.
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'}
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'
getRawValue() |
---|
The aggregate value of the |
|
Retrieves all values regardless of disabled status. |
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'
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'), });
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 });
The options object is used to set a default value for each child control's updateOn
property. If you set updateOn
to 'blur'
at the group level, all child controls default to 'blur', unless the child has explicitly specified a different updateOn
value.
const c = new FormGroup({ one: new FormControl() }, { updateOn: 'blur' });
It is possible to have optional controls in a FormGroup. An optional control can be removed later using removeControl
, and can be omitted when calling reset
. 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 type string|null|undefined
. This is because calling c.reset({})
without providing the optional key one
will cause it to become null
.
© 2010–2023 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/api/forms/FormGroup