Sub topic 8
Two-Way Binding on Form Controls with ngModel
This chapter assumes you already know the banana-in-a-box syntax [( )] from the previous chapter, and that you can create a standalone component with the Angular CLI. Here you apply that syntax to native form controls through the ngModel directive.
Why form controls need a directive
Two-way binding needs two things: a property to write into and an event that reports changes. A native <input> has a value property and an input event. A checkbox uses checked and change, and a <select> behaves differently again. If you wired each control by hand, every control type would need its own property and event pair.
NgModel hides those differences. It is a directive from FormsModule that exposes one input, ngModel, and one output, ngModelChange. Internally it uses a ControlValueAccessor, an adapter that knows how to read and write each kind of control. The result is that [(ngModel)] works the same way on text inputs, checkboxes, radio buttons, selects and textareas.
A working example
Import FormsModule into the component's imports array, then bind each control:
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-settings',
imports: [FormsModule],
template: `
<label>Name <input [(ngModel)]="name"></label>
<label><input type="checkbox" [(ngModel)]="subscribed"> Subscribe</label>
<select [(ngModel)]="theme">
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
<textarea [(ngModel)]="bio"></textarea>
<p>{{ name }} | subscribed: {{ subscribed }} | theme: {{ theme }}</p>
`,
})
export class SettingsComponent {
name = 'Ada';
subscribed = true;
theme = 'dark';
bio = '';
}The checkbox binds to a boolean, and the select binds to the selected option's value. To bind objects rather than strings in a select, use [ngValue] on each option instead of value.
Splitting the binding to add logic
[(ngModel)]="name" is shorthand for [ngModel]="name" (ngModelChange)="name = $event". Write the long form when you need to transform the value or trigger a side effect:
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-username',
imports: [FormsModule],
template: `
<input [ngModel]="username" (ngModelChange)="setUsername($event)">
<p>Saved as: {{ username }}</p>
`,
})
export class UsernameComponent {
username = '';
setUsername(value: string) {
this.username = value.trim().toLowerCase();
}
}Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `Can't bind to 'ngModel' since it isn't a known property of 'input'` | `FormsModule` is not imported | Add `FormsModule` to the component's `imports` |
| Error saying a `name` attribute is required | `ngModel` used inside a `<form>` without `name` | Add `name="..."` or `[ngModelOptions]="{ standalone: true }"` |
| Value updates on every keystroke but you want it on blur | Default update strategy is `change` | Use `[ngModelOptions]="{ updateOn: 'blur' }"` |
| Select shows the right text but the field holds `"[object Object]"` | Used `value` with objects | Use `[ngValue]` |
Exercise
A template contains <form><input [(ngModel)]="email"></form> and FormsModule is imported, yet the console reports an error. What is wrong, and what are two ways to fix it?
Show answer
Inside a form, ngModel must register the control with NgForm under a name, so it requires a name attribute. Fix it by adding name="email" to the input, or by adding [ngModelOptions]="{ standalone: true }" so the control does not register with the form.
Exercise
Rewrite <input [(ngModel)]="price"> so that the field always stores a number, even though the input delivers strings.
Show answer
Split the binding: <input [ngModel]="price" (ngModelChange)="price = +$event">. The unary plus converts the emitted string to a number before it is assigned. Using type="number" on the input also works, because Angular's NumberValueAccessor emits numbers for number inputs.