Sub topic 3
Binding inputs with ngModel
This chapter assumes you can write an Angular standalone component and read its template syntax: property binding, event binding, and template reference variables. It also assumes you know basic HTML form elements and TypeScript classes. By the end you will know what [(ngModel)] expands to, why name matters inside a form, and how the value moves between the template and your class.
What ngModel does
ngModel is a directive from FormsModule. When you put it on an input, Angular creates a FormControl behind the scenes and connects it to the DOM element. The control holds the value, the validation status, and the interaction state. You never construct it yourself. This is why the approach is called template-driven.
ngModel has two jobs:
- It keeps a property in your component class and the visible value of the input in sync.
- It registers the input as a control, and a surrounding
<form>collects it.
The second job is why ngModel is useful even without a value binding. A bare ngModel attribute still creates the control and adds it to the form.
A first working example
The component below binds three inputs to one object. Each input type produces a different JavaScript type.
import { Component } from '@angular/core';
import { JsonPipe } from '@angular/common';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-profile',
imports: [FormsModule, JsonPipe],
template: `
<form>
<label for="name">Name</label>
<input id="name" name="name" [(ngModel)]="profile.name" />
<label for="age">Age</label>
<input id="age" name="age" type="number" [(ngModel)]="profile.age" />
<label>
<input type="checkbox" name="newsletter" [(ngModel)]="profile.newsletter" />
Send me the newsletter
</label>
</form>
<pre>{{ profile | json }}</pre>
`,
})
export class ProfileComponent {
profile = { name: 'Ada', age: 36 as number | null, newsletter: false };
}Type in the name field and the <pre> block updates on every keystroke. Clear the age field and profile.age becomes null, not 0 or an empty string. That is why the property is typed number | null.
| Input | Value written to the model |
|---|---|
| `type="text"` and most others | `string` |
| `type="number"` and `type="range"` | `number`, or `null` when empty |
| `type="checkbox"` | `boolean` |
| `type="radio"` | the `value` of the selected radio |
| `<select>` | the `value` of the selected option |
Angular picks the conversion by choosing a value accessor, a small directive that matches the element and input type. Select, radio, and checkbox inputs get their own chapter, so this one sticks to text, number, and single checkbox.
The banana-in-a-box syntax
[(ngModel)]="profile.name" is shorthand. Angular treats it as a property binding plus an event binding:
<input
name="name"
[ngModel]="profile.name"
(ngModelChange)="profile.name = $event"
/>[ngModel] pushes the model value into the input. (ngModelChange) fires when the user changes the input, and $event holds the new value. The two-way syntax is only a shorter way to write this pair.
Knowing the long form is useful. It lets you do more than assign. This example derives a second value each time the name changes:
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-slug',
imports: [FormsModule],
template: `
<form>
<label for="title">Title</label>
<input
id="title"
name="title"
[ngModel]="title"
(ngModelChange)="onTitleChange($event)"
/>
</form>
<p>Slug: {{ slug }}</p>
`,
})
export class SlugComponent {
title = '';
slug = '';
onTitleChange(value: string) {
this.title = value;
this.slug = value.trim().toLowerCase().replace(/\s+/g, '-');
}
}You can also bind to a signal. In recent Angular versions, [(ngModel)]="title" accepts a writable signal and updates it for you, so title = signal('') works without a handler. Use the split form when you need to run extra logic.
Why name is required inside a form
When ngModel sits inside a <form> tag, Angular needs a key under which to register the control. It reads that key from the name attribute. Without it you get an error like this at runtime:
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.The name becomes the property name in the form's value object. With the inputs from the first example, the form value is { name: 'Ada', age: 36, newsletter: false }. The name attribute and the model path are independent. You can bind [(ngModel)]="profile.name" and still use name="fullName", and the form value will use fullName.
Controls outside the form model
Sometimes an input sits inside a <form> but should not be part of the form value, such as a search box or a UI toggle. Mark it standalone:
<form>
<input name="email" [(ngModel)]="user.email" />
<input
type="search"
[(ngModel)]="filter"
[ngModelOptions]="{ standalone: true }"
/>
</form>The standalone control still keeps its own value and state. It does not need a name, and it does not affect the form's validity or value. Other ngModelOptions settings get their own chapter.
Reading the control with a template reference variable
The directive instance is available through exportAs. Write #name="ngModel" to get a reference to the NgModel directive, which exposes the underlying control's value, valid, touched, and related properties:
<input name="name" [(ngModel)]="profile.name" #name="ngModel" />
<p>Current value: {{ name.value }}</p>Without ="ngModel", the variable points at the DOM element. Then name.value is the raw text of the input, not Angular's view of the control. That difference causes a common mistake: #name gives you an HTMLInputElement and #name="ngModel" gives you the directive. The state properties belong to the directive, and the next chapters build on them.
Timing: the value arrives after the first render
Angular does not write the initial model value into the control during the first change-detection pass. NgModel schedules the write in a resolved promise, so it happens in a microtask right afterward. Two consequences follow.
- Reading
form.valueinngOnInitorngAfterViewInitgives an empty object ornullvalues. The controls are not registered and populated yet. - If you change a bound value synchronously during initialization, you may see
ExpressionChangedAfterItHasBeenCheckederrors when a template expression depends on the control's state.
If you need to act on the populated form, wait one tick. A setTimeout or await Promise.resolve() works for a quick check. In real code it is usually better to react to (ngModelChange) or ngSubmit instead.
One-way versus two-way
Use [ngModel] alone when the template should display the model but the class should decide how changes are handled. Use [(ngModel)] when assigning the new value straight to the property is enough.
A subtle point: with one-way binding and no handler, the user can still type in the input and the control's value changes. The model property in your class does not. The view and the model drift apart until the next time the bound expression changes. If you meant to keep them in sync, add the (ngModelChange) handler or use the banana syntax.
Common errors
- Missing
namein a form. The runtime error shown earlier. Addname, or setstandalone: true. - Forgetting to import
FormsModule. Angular reports thatngModelis not a known property ofinput. AddFormsModuleto the component'simportsarray. - Binding to a getter without a setter. The write side of
[(ngModel)]fails because there is nothing to assign to. Bind to a plain property, a writable signal, or use the split form. - Using
#namewhere#name="ngModel"is needed. The variable is the DOM element, soname.validisundefined. - Expecting a number from a text input. Only
type="number"andtype="range"convert the string. A text input always gives a string, even when the user types digits.
Exercise
A component uses <input [(ngModel)]="city" /> inside a <form>, and the console shows an error saying the name attribute must be set or the control must be standalone. Give two different fixes, and say when you would choose each.
Show answer
Fix 1: add name="city" so the control registers in the form under the key city. Choose this when the value should be part of the form's value and validity. Fix 2: add [ngModelOptions]="{ standalone: true }". Choose this when the input is not part of the submitted data, such as a search filter, so it should not affect the form's value or validity.
Exercise
Rewrite <input name="qty" type="number" [(ngModel)]="qty" /> in its long form using [ngModel] and (ngModelChange), then say what value qty holds after the user empties the field.
Show answer
<input name="qty" type="number" [ngModel]="qty" (ngModelChange)="qty = $event" />. After the field is emptied, qty is null, because the number input's value accessor converts an empty field to null, so the property type should allow null.