Sub topic 4
Grouping Controls with FormGroup
This chapter assumes you know TypeScript generics, standalone Angular components, and how a single FormControl holds a value, a status, and errors. You should already have ReactiveFormsModule available, as set up in an earlier chapter. Here you will combine several controls into one unit with FormGroup. You will see how the group derives its value, status, and interaction state from its children, and you will learn the mistakes people commonly make when they read that derived state.
What a FormGroup is
A FormGroup is a container that maps string keys to child controls. It extends AbstractControl, which is also the base class of FormControl. A group therefore has the same core API as a control: value, status, valid, errors, dirty, touched, and the valueChanges and statusChanges observables.
The difference is where the state comes from. A FormControl stores its own value. A FormGroup stores no value of its own. It computes its value and status from its children and recomputes them every time a child changes.
Creating a group
Pass an object of controls to the constructor. The keys become the names you use later to bind and look up controls.
import { FormControl, FormGroup, Validators } from '@angular/forms';
const profileForm = new FormGroup({
name: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
email: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.email],
}),
});
console.log(profileForm.value); // { name: '', email: '' }
console.log(profileForm.status); // 'INVALID'
profileForm.controls.name.setValue('Ada');
profileForm.controls.email.setValue('[email protected]');
console.log(profileForm.value); // { name: 'Ada', email: '[email protected]' }
console.log(profileForm.valid); // trueIn a component you would usually declare the group as a field, for example profileForm = new FormGroup({...}), so the template can bind to it. The next chapter covers that binding. The model itself is plain TypeScript and runs without any template, which also makes it easy to test.
Accessing child controls
You can reach a child control in two ways.
| Access style | Return type | When to use | Column |
|---|---|---|---|
| `form.controls.email` | `FormControl<string>` | The default choice. TypeScript checks the key and knows the exact control type. | |
| `form.get('email')` | `AbstractControl<string> \ | null` | Dotted paths into nested structures, or keys computed at runtime. |
Prefer controls. If you mistype the key in form.controls.emial, the compiler reports an error. If you mistype it in form.get('emial'), you get null at runtime, and the template fails silently or throws "Cannot read properties of null".
How the group computes its state
Value
form.value is an object built from the values of the enabled children. Disabled children are left out, so the TypeScript type of value is Partial<{ name: string; email: string }>. To get every child's value whatever its disabled state, call getRawValue(). The chapter on disabled controls covers this in detail. For now, keep in mind that value and getRawValue() can differ.
Status
Angular derives the group's status from these rules, checked in order:
- If every child is disabled, the group is
DISABLED. - If the group's own validators return errors, or any enabled child is
INVALID, the group isINVALID. - If any enabled child is
PENDING(an async validator is running), the group isPENDING. - Otherwise the group is
VALID.
Because INVALID is checked before PENDING, a group with one invalid field and one field waiting on a server check reports INVALID. A submit button bound to [disabled]="form.invalid" is therefore disabled in that state. A button bound to form.valid is also disabled while the form is PENDING, which is usually the behavior you want.
Interaction flags
| Flag | True on the group when |
|---|---|
| `dirty` | Any child has been changed through the UI |
| `pristine` | Every child is pristine |
| `touched` | Any child has been blurred |
| `untouched` | Every child is untouched |
Calling form.markAllAsTouched() sets touched on every descendant. It is the usual way to reveal all error messages when the user presses submit on an incomplete form.
The most common mistake: reading errors on the group
form.errors holds only errors produced by validators attached to the group itself. It does not collect child errors.
import { FormControl, FormGroup, Validators } from '@angular/forms';
const form = new FormGroup({
email: new FormControl('not-an-email', {
nonNullable: true,
validators: [Validators.email],
}),
});
console.log(form.invalid); // true
console.log(form.errors); // null
console.log(form.controls.email.errors); // { email: true }
console.log(form.hasError('email', 'email')); // true (second argument is the child path)To show a field's message, read that field's control. To check the group, use form.invalid. Group-level errors only matter when you attach a validator to the group, as cross-field validation does in a later chapter. That validator goes in the second constructor argument:
import { FormControl, FormGroup, ValidationErrors, AbstractControl } from '@angular/forms';
const atLeastOne = (group: AbstractControl): ValidationErrors | null => {
const { phone, email } = group.value as { phone?: string; email?: string };
return phone || email ? null : { contactRequired: true };
};
const contact = new FormGroup(
{
phone: new FormControl('', { nonNullable: true }),
email: new FormControl('', { nonNullable: true }),
},
{ validators: atLeastOne },
);
console.log(contact.errors); // { contactRequired: true }Edge cases and gotchas
- Empty groups are valid.
new FormGroup({}).validistrue. A form built at runtime that ends up with no controls therefore passes validation. Guard against this case explicitly. - Structure changes go through methods. Do not assign to
form.controls.xdirectly. UseaddControl,removeControl, andsetControlso that Angular rewires the parent link and recomputes status. Groups with keys known only at runtime are better modeled withFormRecord, which a later chapter covers. - Controls have one parent. A
FormControlinstance placed in two groups ends up with itsparentpointing at the last group that adopted it. Status bubbling then goes to only one of the groups. Create a separate control for each group. - Reassigning the group field. Replacing
this.profileFormwith a newFormGroupbreaks any subscriptions to the old instance'svalueChanges. Prefer updating the existing group's values, a topic covered in the chapter on setting and patching.
Exercise
A FormGroup has a username control whose async validator is still running and a name control that fails Validators.required. What are form.status and form.errors, and why?
Show answer
form.status is 'INVALID', because Angular checks for invalid children before pending ones. form.errors is null, because the group has no validators of its own. Child errors stay on the child controls.
Exercise
Why is form.controls.email preferred over form.get('email') for a group whose keys are fixed?
Show answer
controls.email is checked at compile time and typed as the exact FormControl<string>. get('email') returns AbstractControl | null, so a typo only shows up at runtime as null, and you need null checks to use the result.
Exercise
You build a group from a server-provided field list, and the list comes back empty. The submit button uses [disabled]="form.invalid". What happens, and how would you prevent it?
Show answer
An empty FormGroup is VALID, so the button is enabled and an empty payload can be submitted. Add a check such as Object.keys(form.controls).length > 0 to the disabled condition, or attach a group validator that returns an error when the group has no controls.