Two-Way Binding with ngModel
ngModel keeps an input box and a class property perfectly in sync — type in one, the other follows.
What you will learn
- Use ngModel for two-way binding
- Import FormsModule so ngModel works
- See the input and class stay in sync live
Both directions at once
Sometimes you want data to flow both ways: the class fills the input, and typing in the input updates the class. Angular bundles this into two-way binding with ngModel and a special syntax called “banana in a box”: [(ngModel)].
Tip: The shape [(ngModel)] is just property binding [ ] and event binding ( ) combined — the brackets inside the parentheses look like a banana in a box.
Turn ngModel on
ngModel lives in Angular’s FormsModule. Import it into your component so the syntax works.
// component class
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-name-box',
standalone: true,
imports: [FormsModule], // makes ngModel available
templateUrl: './name-box.component.html'
})
export class NameBoxComponent {
username = 'Asha';
}Note: Output:
(No visible output — this is setup.)
Adding FormsModule to the imports list switches on the ngModel syntax for this component. The class also starts username at “Asha”, which the input will show first.
Bind an input to a property
<!-- name-box.component.html -->
<input [(ngModel)]="username">
<p>Hello, {{ username }}!</p>Note: Output: The input starts with “Asha” and the page reads “Hello, Asha!”. Type “Ravi” into the box and the line instantly becomes “Hello, Ravi!” — no button needed. The class and the input update each other.
Watch out: If you forget to import FormsModule, Angular throws an error like “Can’t bind to ngModel”. The fix is almost always: add FormsModule to the component’s imports.
Tip: Two-way binding is perfect for form fields — search boxes, name inputs, settings. It saves you wiring up a separate event handler just to read what the user typed.
Q. What does the [(ngModel)] syntax give you?
✍️ Practice
- Bind a text input to a
cityproperty and showYou live in {{ city }}below it. - Add a second input bound to
ageand display both values live.
🏠 Homework
- Build a tiny live preview: an input bound with ngModel that updates a greeting heading as you type.