Sub topic 10
Grouping related controls with ngModelGroup
This chapter assumes you can already bind an input with [(ngModel)], read a control through a template reference variable such as #name="ngModel", and import FormsModule into a standalone component. You also need to know the control states (touched, dirty, valid) from earlier chapters.
What ngModelGroup does
A form with many fields quickly becomes hard to manage as a flat list. Some fields belong together, such as the street, city, and postcode of an address. The ngModelGroup directive collects those controls under one name. It does three things:
- It nests their values under that name in
f.value. - It gives the set its own state:
valid,invalid,touched,dirty,pending, anderrors. - It adds the
ng-validandng-invalidCSS classes (plus the touched and dirty ones) to the element it sits on, so you can style the whole section.
Under the hood, each ngModelGroup creates a FormGroup inside the parent form's FormGroup. You never construct it yourself. The directive registers it for you.
A complete example
The component below groups three address fields. It reads the group through #addr="ngModelGroup" and shows a message when the group is invalid and the user has interacted with it.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-shipping',
imports: [FormsModule],
template: `
<form #f="ngForm" (ngSubmit)="onSubmit(f.value)">
<label for="name">Name</label>
<input id="name" name="name" [(ngModel)]="model.name" required />
<fieldset ngModelGroup="address" #addr="ngModelGroup">
<legend>Address</legend>
<label for="street">Street</label>
<input id="street" name="street" [(ngModel)]="model.address.street" required />
<label for="city">City</label>
<input id="city" name="city" [(ngModel)]="model.address.city" required />
<label for="postcode">Postcode</label>
<input
id="postcode"
name="postcode"
[(ngModel)]="model.address.postcode"
pattern="[0-9]{5}"
required
/>
@if (addr.invalid && addr.touched) {
<p role="alert">Complete every address field before saving.</p>
}
</fieldset>
<p>Address valid: {{ addr.valid }}</p>
<button type="submit" [disabled]="f.invalid">Save</button>
<button type="button" (click)="f.resetForm()">Reset</button>
</form>
`,
})
export class ShippingComponent {
model = {
name: '',
address: { street: '', city: '', postcode: '' },
};
onSubmit(value: unknown) {
console.log('Submitted', value);
}
}If the user fills in everything with the postcode 12345, the submitted value is nested:
{
"name": "Ada",
"address": { "street": "1 Main St", "city": "Springfield", "postcode": "12345" }
}The group name address is only a key in the form value. It does not have to match a property on your model. In this example the match is a convenience, because it makes model.address.street easy to find.
Rules that trip people up
Every control still needs a name
Each ngModel input inside a group needs a name attribute, exactly as it does in a plain form. The name becomes the key inside the group. Without it, Angular throws an error saying the control must have a name or be defined as standalone. The same rule applies to the group itself, which takes its name from the ngModelGroup value.
The group must live inside a form
ngModelGroup looks for a parent NgForm (or another ngModelGroup). If it finds none, it throws an error at runtime. Place it on an element inside the <form>. Use <fieldset> when the fields form a real section, since it also helps assistive technology. Use <div> or <ng-container> when you only need the grouping.
Groups can nest
A group can contain another group, which produces a deeper value object.
<div ngModelGroup="contact">
<input name="email" [(ngModel)]="model.contact.email" />
<div ngModelGroup="phone">
<input name="home" [(ngModel)]="model.contact.phone.home" />
<input name="mobile" [(ngModel)]="model.contact.phone.mobile" />
</div>
</div>This yields { contact: { email, phone: { home, mobile } } }. Keep nesting shallow. Each level adds a path segment you must keep in sync between the template and the model.
Values appear after the first change detection
ngModel and ngModelGroup register their controls asynchronously, in a resolved promise during the first change detection pass. If you read f.value or addr.valid in the constructor or in ngOnInit, you will see an empty object. Read them from event handlers, or from the template, where they update on each render.
Group state
A group's state is computed from its children. The rules differ by property.
| Property | When it is true or what it holds |
|---|---|
| `valid` | Every child control passes its validators and the group's own validators pass. |
| `invalid` | At least one child fails, or a group-level validator fails. |
| `pending` | At least one child is running an async validator. |
| `touched` | At least one child has lost focus. |
| `dirty` | The user has changed at least one child. |
| `errors` | Only errors from group-level validators, not errors from the children. |
| `value` | An object with one key per child control. |
The last two rows cause the most confusion. A group whose street field is empty is invalid, but addr.errors is null, because the required error belongs to the street control. To show a specific child error, read it from the child: addr.control.get('street')?.errors, or use a template variable on the input itself.
Displaying group-level feedback
Use the group state to avoid cluttering the page with one message per field. A single message that appears once the user has touched any field in the group is often enough:
@if (addr.invalid && addr.touched) {
<p role="alert">Complete every address field before saving.</p>
}Because touched flips when any child blurs, this message can appear while the user is still on the first field of the group and has not yet reached the others. If that is too eager, combine it with the form's submitted state. Template variable f exposes f.submitted, which becomes true after the first submit event:
@if (addr.invalid && (addr.touched || f.submitted)) {
<p role="alert">Complete every address field before saving.</p>
}Keep role="alert" on the container so screen readers announce the message when it appears.
Styling the group
Angular adds state classes to the element that carries ngModelGroup. With the <fieldset> above, you can write:
fieldset.ng-invalid.ng-touched {
border: 2px solid #b00020;
}The group's classes reflect the whole group, so one invalid child turns the whole fieldset red once something inside it has been touched.
Reading and changing a group programmatically
The directive's control property is the underlying FormGroup. Through it you can set or read part of the form without touching the rest.
import { Component, viewChild } from '@angular/core';
import { FormsModule, NgModelGroup } from '@angular/forms';
@Component({
selector: 'app-address-loader',
imports: [FormsModule],
template: `
<form #f="ngForm">
<div ngModelGroup="address">
<input name="street" [(ngModel)]="model.address.street" />
<input name="city" [(ngModel)]="model.address.city" />
</div>
<button type="button" (click)="fillDefaults()">Use office address</button>
</form>
`,
})
export class AddressLoaderComponent {
model = { address: { street: '', city: '' } };
group = viewChild(NgModelGroup);
fillDefaults() {
this.group()?.control.patchValue({ street: '5 Office Rd', city: 'Springfield' });
}
}patchValue accepts a partial object. setValue requires every key in the group and throws if one is missing. Prefer patchValue when you only know some of the fields.
For the whole form, f.resetForm() clears all values and resets every control and group to pristine and untouched. You can pass a value to reset to defaults, for example f.resetForm({ address: { city: 'Springfield' } }). Calling f.reset() clears values but leaves the form's submitted flag set, so resetForm() is usually the right choice after a successful submit.
Group-level validators
You can attach a validator directive to the group itself. The same NG_VALIDATORS mechanism you used for a single control works on ngModelGroup. The validator receives the group, so it can inspect several children at once.
import { Directive } from '@angular/core';
import {
AbstractControl,
NG_VALIDATORS,
ValidationErrors,
Validator,
} from '@angular/forms';
@Directive({
selector: '[ngModelGroup][cityWithPostcode]',
standalone: true,
providers: [
{ provide: NG_VALIDATORS, useExisting: CityWithPostcodeDirective, multi: true },
],
})
export class CityWithPostcodeDirective implements Validator {
validate(group: AbstractControl): ValidationErrors | null {
const postcode = group.get('postcode')?.value;
const city = group.get('city')?.value;
return postcode && !city ? { cityWithPostcode: true } : null;
}
}Use it as <div ngModelGroup="address" cityWithPostcode #addr="ngModelGroup">, and import the directive in the component. Now addr.errors?.['cityWithPostcode'] is set when a postcode exists without a city. The optional chaining in group.get(...)?.value matters, because on the first validation pass some children may not be registered yet. A later chapter covers cross-field validation in more depth.
Common mistakes
- Putting
ngModelGroupon an element outside the<form>, which throws at runtime. - Forgetting
nameon a control inside the group. - Expecting
addr.errorsto list child errors. - Using
setValuewith a partial object instead ofpatchValue. - Reading
f.valuetoo early, before the controls have registered. - Disabling a control and expecting it in
f.value. Disabled controls are left out ofvalue, butf.getRawValue()includes them.
Exercise
A form contains <div ngModelGroup="address"> with a required street input and a required city input, both empty. What are addr.valid, addr.errors, and the shape of f.value after the user types "Main St" into street and "Springfield" into city? Why is addr.errors not helpful for showing "street is required"?
Show answer
Initially addr.valid is false, because the required children are empty, and addr.errors is null, because errors holds only group-level validator results and the required error belongs to the street control. After both fields are filled, addr.valid is true and f.value is { address: { street: 'Main St', city: 'Springfield' } }. To show "street is required", read the child's errors, for example addr.control.get('street')?.errors?.['required'], or use #street="ngModel" on the input.
Exercise
You want a button that fills only the city field of the address group without clearing street. Which method on NgModelGroup.control should you call, and why not the other one?
Show answer
Call patchValue({ city: 'Springfield' }). It updates only the keys you provide. setValue requires a value for every control in the group and throws an error when a key is missing.