Sub topic 11
Modeling Structured Data with Nested Groups
This chapter assumes you can already create a FormGroup, bind it with [formGroup] and formControlName, and read valid, touched, and errors on a control. You should also know how nonNullable controls affect typing. Real data is rarely flat. A customer has an address, an address has a street and a city, and a checkout form may have separate billing and shipping addresses. Nested groups let the form model match that shape.
Why Nest Groups at All
A FormGroup can hold any AbstractControl as a child, including another FormGroup. When you nest groups, three things follow:
- The form's value has the same nested shape as your domain object, so you can send it to an API without remapping fields.
- Validity bubbles up the tree. If any control inside
addressis invalid,addressis invalid, and so is the root form. - You can treat a branch as one unit. You can reset it, disable it, patch it, or validate it as a whole.
You could keep everything flat with names like addressStreet and addressCity. That works for small forms, but you then write mapping code by hand, and you lose the ability to work with the address as a unit.
Defining a Nested Model
The component below models a contact with a nested address group. Every control is non-nullable, so reset() restores the initial values instead of setting them to null.
import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-contact-form',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="contactForm" (ngSubmit)="onSubmit()">
<label>
Name
<input formControlName="name" />
</label>
<fieldset formGroupName="address">
<legend>Address</legend>
<label>
Street
<input formControlName="street" />
</label>
<label>
City
<input formControlName="city" />
</label>
<label>
Postcode
<input formControlName="postcode" />
</label>
@if (address.invalid && address.touched) {
<p>Complete the address.</p>
}
</fieldset>
<button type="submit" [disabled]="contactForm.invalid">Save</button>
</form>
`,
})
export class ContactFormComponent {
contactForm = new FormGroup({
name: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
address: new FormGroup({
street: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
city: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
postcode: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.pattern(/^\d{5}$/)],
}),
}),
});
get address() {
return this.contactForm.controls.address;
}
onSubmit(): void {
console.log(this.contactForm.getRawValue());
// { name: '...', address: { street: '...', city: '...', postcode: '...' } }
}
}The formGroupName="address" directive looks up the child group named address on the closest parent formGroup. The formControlName directives inside the fieldset then resolve against address, not against the root. Each directive resolves its name relative to the nearest group directive above it in the DOM.
Reaching Nested Controls in Code
You have two ways to get at a nested control.
| Approach | Example | Typing | When to use |
|---|---|---|---|
| `controls` chain | `form.controls.address.controls.city` | Fully typed, never `null` | Default choice in typed forms |
| `get()` with a path | `form.get('address.city')` | Typed from the path literal, but may be `null` | Paths built at runtime, or short template expressions |
The controls chain catches typos at compile time. The get() method takes a dotted string, or an array such as ['address', 'city'], and returns null when the path does not exist. With a string literal, typed forms infer the control type from the path. A path built at runtime gives you a loosely typed result.
const city = this.contactForm.controls.address.controls.city;
city.setValue('Lisbon');
const postcode = this.contactForm.get('address.postcode');
console.log(postcode?.hasError('pattern'));Updating Nested Values
setValue and patchValue work through the whole tree, and their strictness carries down to every level.
// patchValue: any subset, at any depth
this.contactForm.patchValue({ address: { city: 'Porto' } });
// setValue on the branch: every key of address is required
this.contactForm.controls.address.setValue({
street: 'Rua Augusta 10',
city: 'Lisbon',
postcode: '11000',
});
// reset only the branch
this.contactForm.controls.address.reset();When you call setValue on the root, you must supply the full nested object. A missing address.postcode throws an error at runtime, and typed forms also flag it at compile time. patchValue skips any keys you leave out, at every depth.
How Status Propagates
A change to a leaf control recalculates the status of each ancestor, from the leaf up to the root. A group's status follows these rules:
INVALIDif any enabled child is invalid, or if the group's own validators fail.PENDINGif no child is invalid but at least one is waiting on an async validator.DISABLEDonly when every child is disabled.VALIDotherwise.
touched and dirty also roll up. A group is touched as soon as any descendant is touched. That is why the template above can show one message for the whole address once the user leaves any of its fields. Calling markAllAsTouched() on the root marks every nested control, which is useful when you want all errors to appear on submit.
Splitting a Branch into a Child Component
Large forms often move a nested group into its own component. The simplest pattern passes the group in as an input and binds it with its own [formGroup].
import { Component, input } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
export type AddressGroup = FormGroup<{
street: FormControl<string>;
city: FormControl<string>;
postcode: FormControl<string>;
}>;
@Component({
selector: 'app-address-fields',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<div [formGroup]="group()">
<input formControlName="street" placeholder="Street" />
<input formControlName="city" placeholder="City" />
<input formControlName="postcode" placeholder="Postcode" />
</div>
`,
})
export class AddressFieldsComponent {
group = input.required<AddressGroup>();
}The parent then renders <app-address-fields [group]="address" />. The child holds no form state of its own. It only binds to the branch it was given, so validity and value still roll up into the parent form.
Common Errors
formGroupName must be used with a parent formGroup directive. TheformGroupNameelement sits outside the element that carries[formGroup], often after a template is split into components. Either pass the group as an input, as shown above, or provideControlContainerin the child'sviewProviders.- Dotted names in
formControlName.formControlName="address.city"does not work. Wrap the input informGroupName="address"and useformControlName="city". setValuewith a partial nested object. This throwsMust supply a value for form control with name: 'postcode'. UsepatchValueinstead.- Reading
valuewith disabled children. A disabled nested control drops out ofvalue. UsegetRawValue()when you need the complete object.
Exercise
A form has a nested billing group containing street and zip. The user has touched only billing.zip, which is empty and required. What are form.touched, form.controls.billing.touched, and form.valid? And why does form.setValue({ billing: { street: 'Main St' } }) fail?
Show answer
All three flags follow from roll-up: form.touched is true and billing.touched is true, because touched propagates up from any descendant. form.valid is false, because the invalid zip makes billing invalid, which makes the root invalid. setValue fails because it requires a value for every control at every level, and zip is missing. Use patchValue for a partial update.
Exercise
Why is form.controls.billing.controls.zip usually preferred over form.get('billing.zip') in a strictly typed form?
Show answer
The controls chain is checked at compile time and always returns a non-null, fully typed FormControl. get() returns a possibly null result, and a typo in the path string only shows up at runtime as null.