Sub topic 8
Two-Way Binding on Form Controls with ngModel
The previous chapter showed that [(x)] is shorthand for a property binding [x] plus an event binding (xChange). Native HTML elements have no value/valueChange pair that follows this naming rule, so Angular ships a directive that adds one: NgModel. This chapter explains how ngModel works, how it handles each type of form control, and the errors developers most often run into with it.
This chapter assumes you know the banana-in-a-box syntax from the previous chapter, property and event binding, and how to create a standalone component with the Angular CLI. Template reference variables come up again here briefly.
Importing FormsModule
NgModel is part of @angular/forms and is not available to templates by default. A standalone component has to add FormsModule to its imports array:
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-greeting',
imports: [FormsModule],
template: `
<input [(ngModel)]="name">
<p>Hello, {{ name }}!</p>
`,
})
export class GreetingComponent {
name = 'World';
}If you forget the import, compilation fails with:
NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'.The message is misleading. Your binding is fine. The compiler never matched a directive with an ngModel input, so it fell back to treating ngModel as a DOM property and found no such property on <input>. Whenever you see this error, check the component's imports first.
What ngModel Expands To
[(ngModel)]="name" desugars exactly like any other two-way binding:
<input [ngModel]="name" (ngModelChange)="name = $event">NgModel has an @Input() ngModel and an @Output() ngModelChange, so the standard naming rule applies. The work of talking to the actual DOM element happens in a separate layer: the control value accessor.
A control value accessor is a directive that implements the ControlValueAccessor interface. It knows how to write a value into one kind of element (writeValue) and how to report changes coming from it (registerOnChange, registerOnTouched). FormsModule includes accessors for the built-in controls, and each one picks out its elements with a CSS selector. NgModel finds the accessor on the same element through dependency injection and passes values through it.
Built-in value accessors
| Element | Accessor | Model value type |
|---|---|---|
| `<input>` (text, email, etc.), `<textarea>` | `DefaultValueAccessor` | `string` |
| `<input type="checkbox">` | `CheckboxControlValueAccessor` | `boolean` |
| `<input type="number">` | `NumberValueAccessor` | `number` or `null` when empty |
| `<input type="range">` | `RangeValueAccessor` | `number` |
| `<input type="radio">` | `RadioControlValueAccessor` | the `value` of the checked radio |
| `<select>` | `SelectControlValueAccessor` | the `value` or `ngValue` of the selected option |
| `<select multiple>` | `SelectMultipleControlValueAccessor` | array of selected values |
The type column matters in practice. A type="number" input gives your field a real number. Without the type attribute, the DefaultValueAccessor is used and you get the string "42".
Binding Each Control Type
The component below binds every common control type and displays the resulting model values with their runtime types.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
interface Plan {
id: number;
label: string;
}
@Component({
selector: 'app-settings',
imports: [FormsModule],
template: `
<label>Display name <input [(ngModel)]="displayName"></label>
<label>
<input type="checkbox" [(ngModel)]="newsletter"> Newsletter
</label>
<label>Age <input type="number" [(ngModel)]="age"></label>
<label>Plan
<select [(ngModel)]="plan" [compareWith]="samePlan">
@for (p of plans; track p.id) {
<option [ngValue]="p">{{ p.label }}</option>
}
</select>
</label>
<label><input type="radio" name="theme" value="light" [(ngModel)]="theme"> Light</label>
<label><input type="radio" name="theme" value="dark" [(ngModel)]="theme"> Dark</label>
<ul>
<li>displayName: {{ displayName }} ({{ typeOf(displayName) }})</li>
<li>newsletter: {{ newsletter }} ({{ typeOf(newsletter) }})</li>
<li>age: {{ age }} ({{ typeOf(age) }})</li>
<li>plan: {{ plan.label }} (id {{ plan.id }})</li>
<li>theme: {{ theme }}</li>
</ul>
`,
})
export class SettingsComponent {
plans: Plan[] = [
{ id: 1, label: 'Free' },
{ id: 2, label: 'Pro' },
];
displayName = 'Ada';
newsletter = true;
age: number | null = 36;
// A different object instance from plans[1], e.g. loaded from an API
plan: Plan = { id: 2, label: 'Pro' };
theme = 'dark';
samePlan(a: Plan | null, b: Plan | null): boolean {
return a?.id === b?.id;
}
typeOf(value: unknown): string {
return typeof value;
}
}Several details in this example matter:
[value]on an<option>always produces a string.[ngValue]lets you bind any value, including objects.- With objects, the select compares by reference by default.
planhere is a different instance fromplans[1], so without[compareWith]nothing would appear selected.compareWithtakes a function(a, b) => boolean, and that function is called without your component asthis. Don't read component state inside it. - Radio buttons in a group share a single model field. The
nameattribute groups them in the DOM, and the radio accessor uses it as well. - Clearing the number input sets
agetonullrather than0or"". Type the field to allownull.
ngModel Inside a form Element
When an ngModel sits inside a <form>, FormsModule automatically puts the NgForm directive on that form, and each NgModel registers itself with NgForm as a named control. Registering needs a name, so this template throws at runtime:
<form>
<input [(ngModel)]="email">
</form>NG01352: 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.There are two ways to fix it:
<form>
<!-- Registered with the form as "email" -->
<input name="email" [(ngModel)]="email">
<!-- Bound to the field, but not part of the form's value or validity -->
<input [(ngModel)]="search" [ngModelOptions]="{ standalone: true }">
</form>Two inputs inside the same form must not share a name unless they are radios in one group. If they do, the second registration replaces the first, and the form value and validity no longer match what is on screen.
Reading Control State with a Template Reference Variable
NgModel exports itself as ngModel. If you assign it to a template reference variable, you can read the control's validation and interaction state. FormsModule also includes validator directives for required, email, minlength, maxlength and pattern.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-signup',
imports: [FormsModule],
template: `
<form #f="ngForm" (ngSubmit)="submit()">
<input name="email" type="email" required email
[(ngModel)]="email" #emailCtrl="ngModel">
@if (emailCtrl.invalid && emailCtrl.touched) {
@if (emailCtrl.errors?.['required']) {
<p>Email is required.</p>
} @else if (emailCtrl.errors?.['email']) {
<p>That is not a valid email.</p>
}
}
<button [disabled]="f.invalid">Sign up</button>
</form>
`,
})
export class SignupComponent {
email = '';
submit() {
console.log('Submitting', this.email);
}
}Without ="ngModel", #emailCtrl would point to the HTMLInputElement, which has no errors or touched property. For the same reason, #f="ngForm" gives you the NgForm directive instead of the <form> element.
Splitting the Binding: Transforming Values
Sometimes the value needs to change on its way into the model. Use the expanded form and handle ngModelChange yourself:
<input [ngModel]="code" (ngModelChange)="code = $event.toUpperCase()">In the handler, always read the new value from $event. If you also write [(ngModel)] and a separate (ngModelChange) on the same element, both handlers run in the order they appear in the template. A handler placed before [(ngModel)] reads the old value from the field. Using $event avoids depending on that order.
Controlling When the Model Updates
By default, the model updates on every input event. ngModelOptions can delay updates until blur, or (inside a form) until submit:
<input name="username" [(ngModel)]="username" [ngModelOptions]="{ updateOn: 'blur' }">This is useful when every change triggers expensive work, such as an HTTP availability check. Validation runs on the same schedule, so errors show up only after the user leaves the field.
Using ngModel with Signals
As of Angular 17.2, two-way binding accepts a WritableSignal directly. Angular reads the signal for the property side and calls .set() for the event side:
import { Component, computed, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-search',
imports: [FormsModule],
template: `
<input [(ngModel)]="query" placeholder="Search">
<p>{{ resultLabel() }}</p>
`,
})
export class SearchComponent {
query = signal('');
resultLabel = computed(() =>
this.query() ? 'Searching for "' + this.query() + '"' : 'Type to search'
);
}Write [(ngModel)]="query", not [(ngModel)]="query()". A call expression can't be assigned to, so the compiler rejects it. Only writable signals work here. A computed() or a signal input() is read-only.
Timing Gotcha: ngModel Writes Asynchronously
NgModel applies a new input value inside a resolved promise, a microtask after change detection processes the binding. As a result, code that runs synchronously during initialization can see the control's value as empty:
import { AfterViewInit, Component, ViewChild } from '@angular/core';
import { FormsModule, NgForm } from '@angular/forms';
@Component({
selector: 'app-timing',
imports: [FormsModule],
template: `<form #f="ngForm"><input name="city" [(ngModel)]="city"></form>`,
})
export class TimingComponent implements AfterViewInit {
@ViewChild('f') form!: NgForm;
city = 'Oslo';
ngAfterViewInit() {
console.log(this.form.value); // { city: null }
Promise.resolve().then(() => console.log(this.form.value)); // { city: 'Oslo' }
}
}Read your component field (this.city) when you need the current value at startup, or subscribe to form.valueChanges. Don't rely on reading the form's value synchronously.
Exercises
Exercise
A component imports FormsModule and its template contains <form><input [(ngModel)]="title"></form>. The app compiles but throws NG01352 at runtime. Give two different fixes and explain how they differ.
Show answer
Add name="title" so the control registers with the enclosing NgForm under that name, or add [ngModelOptions]="{ standalone: true }" so it binds to the field without registering. With the name, the control is part of form.value and affects form.valid. With standalone, the form ignores it.
Exercise
A select uses <option [value]="p"> for each plan object, and the bound field ends up holding the string "[object Object]". Why, and what should the template use instead? What else is needed if the field starts as a separate object fetched from an API?
Show answer
[value] sets the option's DOM value, which is always a string, so the object is converted to "[object Object]". Use [ngValue]="p" so the accessor keeps the real object. Because the fetched object is a different instance, add [compareWith] on the select with a function that compares ids, otherwise no option appears selected.
Exercise
You write <input [(ngModel)]="query()"> where query = signal(''). What happens, and what is the correct template?
Show answer
Compilation fails, because the event half of the binding would assign to a call expression. Write [(ngModel)]="query". Angular recognizes the writable signal, reads it for the property side and calls query.set($event) on change.