Sub topic 10
Grouping related controls with ngModelGroup
This chapter assumes you can write an Angular standalone component, bind inputs with [(ngModel)], and read a form through #f="ngForm". If any of that is unfamiliar, review the earlier chapters on ngModel and NgForm first.
Why group controls
A form often has fields that belong together, such as the street and city of an address. Without grouping, f.value is a flat object with one key per control. With ngModelGroup, Angular nests those controls under a single key. It also gives you one validity state for the whole group.
Grouping gives you three things:
- A nested shape in
f.valuethat can match your data model. - A single
valid,dirty, andtouchedstate for the group. - A place to attach group-level validation later.
Creating a group
Add the ngModelGroup directive to any element that wraps the controls. The directive's value becomes the key in the form value. Each control inside still needs its own name attribute.
<form #f="ngForm" (ngSubmit)="save(f.value)">
<div ngModelGroup="address" #addr="ngModelGroup">
<input name="street" [(ngModel)]="model.address.street" required />
<input name="city" [(ngModel)]="model.address.city" required />
</div>
<p>Address valid: {{ addr.valid }}</p>
<button type="button" (click)="f.resetForm()">Reset</button>
</form>The expression #addr="ngModelGroup" exports the directive instance into a template reference variable, in the same way #f="ngForm" exports the form. You can then read addr.valid, addr.invalid, addr.dirty, addr.touched, and addr.errors.
For this template, f.value looks like this:
const value = {
address: { street: 'Main St', city: 'Springfield' },
};The model object in the component should have the same nested shape. Initialize every level, or the binding model.address.street throws an error at render time.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-address',
imports: [FormsModule],
templateUrl: './address.component.html',
})
export class AddressComponent {
model = { address: { street: '', city: '' } };
save(value: unknown) {
console.log('Saved', value);
}
}How group state is computed
A group's state is derived from its children.
| Group state | When it is true |
|---|---|
| `valid` | Every control in the group is valid. |
| `invalid` | At least one control in the group is invalid. |
| `dirty` | The user changed at least one control. |
| `touched` | The user blurred at least one control. |
The parent form uses the same rule over its groups. An invalid group makes f.invalid true, so a button bound to [disabled]="f.invalid" stays disabled until the group is fixed.
Showing a group-level message
Use the group variable to show one message instead of one per field.
<div ngModelGroup="address" #addr="ngModelGroup">
<input name="street" [(ngModel)]="model.address.street" required />
<input name="city" [(ngModel)]="model.address.city" required />
</div>
@if (addr.invalid && addr.touched) {
<p role="alert">Please complete the address.</p>
}The touched check keeps the message hidden until the user has interacted with the group.
Resetting
f.resetForm() clears every value and returns all controls and groups to pristine and untouched. Pass an object to reset to specific values, for example f.resetForm({ address: { street: '', city: '' } }). Calling f.reset() also clears values, but it does not reset the submitted state.
Common errors
- Missing
nameon a control inside the group. Angular throws an error becausengModelneeds a name to register the control. - Group variable used outside the form.
ngModelGroupmust be inside aNgForm. Otherwise Angular reports that it has no parent. - Uninitialized nested model.
model.addressmust exist before the template renders. - Reusing a group name. Two groups with the same name merge into one key and overwrite each other.
Exercise
A form has <div ngModelGroup="address"> that contains two required inputs named street and city. The user fills in street and leaves city empty. What are addr.valid and f.value.address.city?
Show answer
addr.valid is false, because one required control in the group is invalid. f.value.address.city is an empty string (or whatever the bound model holds), because the control is still registered and keeps its current value.