Angular BasicsCore· 35 min read

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.

Import FormsModule to enable ngModel
// 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

Two-way binding: input and property stay in sync
<!-- 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?

Answer: ngModel with the “banana in a box” brackets binds an input both ways — changes in either the input or the property update the other.

✍️ Practice

  1. Bind a text input to a city property and show You live in {{ city }} below it.
  2. Add a second input bound to age and display both values live.

🏠 Homework

  1. Build a tiny live preview: an input bound with ngModel that updates a greeting heading as you type.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →