Two-way binding with ngModel lets your app keep the data and the user interface in sync automatically. When the user changes input, the data updates, and when the data changes, the input updates.
0
0
Two-way binding with ngModel in Angular
Introduction
When you want to update a form input and keep the data model updated at the same time.
When you want to show live changes in the UI as the user types or selects options.
When building simple forms where you want to avoid writing extra event handlers.
When you want to bind input fields like text boxes, checkboxes, or selects to variables easily.
Syntax
Angular
<input [(ngModel)]="propertyName" />The [( )] syntax is called the banana-in-a-box and means two-way binding.
You must import FormsModule in your Angular module to use ngModel.
Examples
Binds the input value to the
username variable. Changes in input update username, and changes to username update the input.Angular
<input [(ngModel)]="username" />Binds a number input to the
age property inside the user object.Angular
<input [(ngModel)]="user.age" type="number" />
Binds a dropdown select to the
selectedColor variable.Angular
<select [(ngModel)]="selectedColor"> <option value="red">Red</option> <option value="blue">Blue</option> </select>
Sample Program
This component uses ngModel to bind the input box to the name variable. When you type your name, the greeting updates live below.
Angular
import { Component } from '@angular/core'; import { FormsModule } from '@angular/forms'; @Component({ selector: 'app-two-way-binding', standalone: true, imports: [FormsModule], template: ` <label for="nameInput">Enter your name:</label> <input id="nameInput" [(ngModel)]="name" /> <p>Hello, {{ name }}!</p> ` }) export class TwoWayBindingComponent { name = ''; }
OutputSuccess
Important Notes
Remember to import FormsModule in your Angular module or use standalone components with imports: [FormsModule] to enable ngModel.
Two-way binding is great for simple forms but can be less clear in complex apps where reactive forms or explicit event handling might be better.
Summary
Two-way binding with ngModel keeps data and UI in sync automatically.
Use the [(ngModel)] syntax on form controls like inputs and selects.
Make sure to import FormsModule to use ngModel.