Sub topic 12
Tuning behavior with ngModelOptions
This chapter assumes you can already bind an input with [(ngModel)] and read control state through template reference variables such as #name="ngModel". It also assumes you know what touched, dirty and valid mean, and that you have used FormsModule in a standalone component.
ngModelOptions changes how an ngModel control talks to its model. It covers three things:
- when the control takes a new value from the view
- what name the control registers under
- whether the control joins the parent form at all
What the options are
You pass the options as an object through a property binding on any element that has ngModel.
| Option | Type | Effect |
|---|---|---|
| `updateOn` | `'change'`, `'blur'` or `'submit'` | Chooses the event that pushes the view value into the control. The default is `'change'`. |
| `name` | `string` | Sets the control's name. It is an alternative to the `name` attribute. |
| `standalone` | `boolean` | When `true`, the control is not registered with the enclosing `NgForm`. |
Bind the options with square brackets: [ngModelOptions]="{ updateOn: 'blur' }". A plain attribute such as ngModelOptions="{ updateOn: 'blur' }" passes a string, not an object, so the options are ignored.
How updateOn changes the data flow
By default every keystroke fires the input's input event. Angular copies the new text into the control, runs the validators, updates the model, and emits ngModelChange. With updateOn: 'blur' or 'submit', Angular still notices each keystroke, but it holds the value as pending and delays the update.
The practical effects:
- Validators run only when the value is applied. With
'blur', a user typing an invalid email sees no error until they leave the field. This is the main reason to use it: it avoids "Invalid email" flashing while someone is still typing. - The model stays old while the user types.
model.emailin your component does not change until the update event. A live preview bound to the model will not move on every keystroke. dirtyis delayed. Angular records the change as pending and marks the control dirty when it applies the value. The control stays pristine while the user types in a'blur'or'submit'control.toucheddepends on the mode. A blur marks the control touched for'change'and'blur'. With'submit', blur does not mark it touched.- Model-to-view updates are unaffected. Programmatic changes still reach the input immediately.
Setting the mode on one control
This component uses a single control with updateOn: 'blur'. The <p> elements show the model so you can watch when it changes.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-email-blur',
imports: [FormsModule],
template: `
<form #f="ngForm" (ngSubmit)="onSubmit()">
<label for="email">Email</label>
<input
id="email"
name="email"
type="email"
[(ngModel)]="model.email"
[ngModelOptions]="{ updateOn: 'blur' }"
#email="ngModel"
required
email
/>
<p>Model value: {{ model.email }}</p>
@if (email.invalid && email.touched) {
<p role="alert">Enter a valid email address.</p>
}
<button type="submit" [disabled]="f.invalid">Save</button>
</form>
`,
})
export class EmailBlurComponent {
model = { email: '' };
onSubmit() {
console.log('Submitted', this.model);
}
}Type in the field and watch "Model value". It stays empty until you tab away.
[disabled]="f.invalid" also lags. While the user is still typing a valid address in an empty required field, the form is still invalid. The Save button enables only after blur. If the user clicks Save directly from the field, the click moves focus first, so the blur applies the value before the form is read. Test that path anyway.
Setting the mode for the whole form
Put ngFormOptions on the <form> to set the default for every control inside it. A control's own ngModelOptions overrides it.
<form #f="ngForm" [ngFormOptions]="{ updateOn: 'blur' }" (ngSubmit)="save()">
<input name="email" [(ngModel)]="model.email" required email />
<input
name="nickname"
[(ngModel)]="model.nickname"
[ngModelOptions]="{ updateOn: 'change' }"
/>
<button type="submit">Save</button>
</form>Here email updates on blur because of the form default. nickname updates on every keystroke because it overrides the default.
Using updateOn: 'submit'
With 'submit', no control applies its value until the form is submitted. Angular synchronizes all pending controls first, then emits ngSubmit. Your handler therefore always sees the final values.
<form #f="ngForm" [ngFormOptions]="{ updateOn: 'submit' }" (ngSubmit)="login(f.value)">
<input name="user" [(ngModel)]="model.user" required />
<input name="password" type="password" [(ngModel)]="model.password" required />
@if (f.submitted && f.invalid) {
<p role="alert">Fill in both fields.</p>
}
<button type="submit">Log in</button>
</form>Two consequences matter here:
- Validation feedback only appears after the first submit attempt. The state flags
touchedanddirtynever turn on before that, so thetouched || dirtypattern from earlier chapters shows nothing. Usef.submitted, which istrueonce the form has been submitted. - A disabled submit button deadlocks.
[disabled]="f.invalid"keeps the form invalid until a submit, and a disabled button cannot submit. Leave the button enabled in this mode.
resetForm() clears pending values along with control state, so a reset after a failed submit returns to a clean slate.
Keeping a control out of the form
Every ngModel inside a <form> must have a name, because Angular uses it as the key in f.value. A missing name throws an error at runtime: "If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions."
If the control is not part of the submitted data, such as a filter box or a display toggle, mark it standalone:
<form #f="ngForm" (ngSubmit)="save(f.value)">
<input name="title" [(ngModel)]="model.title" required />
<input
[(ngModel)]="filterText"
[ngModelOptions]="{ standalone: true }"
placeholder="Filter suggestions"
/>
<button type="submit">Save</button>
</form>A standalone control still has its own value, validity and state, and you can still read them through #filter="ngModel". It simply does not appear in f.value and does not affect f.valid. A required standalone field will not block the form.
You can also supply the name through the options, as in [ngModelOptions]="{ name: 'city' }". This is rarely needed, but it helps when a name comes from a variable and you prefer to keep it with the other options.
Debouncing is not an option
There is no debounce setting in template-driven forms. If you want to wait for the user to pause typing, for example before calling a search API, split the binding and handle it with RxJS or a timer:
import { Component, OnDestroy } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Subject, Subscription, debounceTime, distinctUntilChanged } from 'rxjs';
@Component({
selector: 'app-search-box',
imports: [FormsModule],
template: `
<input
name="q"
[ngModel]="query"
(ngModelChange)="input$.next($event)"
aria-label="Search"
/>
<p>Searching for: {{ query }}</p>
`,
})
export class SearchBoxComponent implements OnDestroy {
query = '';
input$ = new Subject<string>();
private sub: Subscription = this.input$
.pipe(debounceTime(300), distinctUntilChanged())
.subscribe((value) => (this.query = value));
ngOnDestroy() {
this.sub.unsubscribe();
}
}The control still updates on each keystroke, so its validators run immediately. Only your own query field is debounced.
Common errors
- Options silently ignored. The attribute form
ngModelOptions="{...}"is a string. Use[ngModelOptions]. - Error messages never appear. You used
'submit'but kept atouchedordirtycondition. Switch tof.submitted. - Submit button stuck disabled. The form is invalid because no value has been applied yet. Under
'blur'it recovers on blur. Under'submit'it never does. - Live preview does not update. The model changes only on the update event. Bind the preview to the control's
value, or keep the control on'change'. - Unexpected form-wide behavior. A control-level
ngModelOptionsoverridesngFormOptions, but only for the keys it sets. Check both when behavior surprises you. - Name error at startup. A control inside a
<form>has neithernamenorstandalone: true.
Exercise
A signup form uses [ngFormOptions]="{ updateOn: 'submit' }". The password field shows its error with @if (pw.invalid && pw.touched), but the error never appears, even after the user submits an empty form. Why, and what condition fixes it?
Show answer
With updateOn 'submit', blurring a control does not mark it touched, and dirty is not set until the value is applied. Neither flag is true before submit, so the condition stays false. Use f.submitted, for example @if (pw.invalid && f.submitted), where f is the NgForm template reference variable.
Exercise
A form contains a "Filter countries" input bound with [(ngModel)]="filter" and no name attribute. The app throws an error at startup, and you do not want the filter included in f.value. What is the smallest change that fixes it?
Show answer
Add [ngModelOptions]="{ standalone: true }" to the filter input. The control then does not register with the NgForm, so no name is required, it is absent from f.value, and its validity does not affect f.valid.