13. Two-Way Data Binding [(ngModel)]
Two-way data binding synchronizes data flow between the component class and the template view simultaneously. Changes in the component update the view, and changes in the view update the component model.
The Banana in a Box [()]
Angular uses the special [()] syntax, often called the 'banana in a box', to denote two-way binding. It is syntactic sugar for combining property binding ([]) and event binding (()):
html [(ngModel)]="dataProperty"
// is equivalent to:
[ngModel]="dataProperty" (ngModelChange)="dataProperty = $event"
Requirements: FormsModule
Two-way binding primarily uses the ngModel directive, which is part of Angular's FormsModule. You must import this module into your NgModule to use ngModel.
app.module.ts update:
typescript import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; // 1. Import FormsModule
@NgModule({ imports: [BrowserModule, FormsModule], // 2. Add to imports array // ... }) export class AppModule { }
Two-Way Binding Example
Component Class:
typescript export class LoginComponent { username: string = 'initial_user'; }
Template:
html
User Profile Editor
<input type="text" [(ngModel)]="username">
Model value is: {{ username }}
Two-way binding is incredibly convenient for simple data entry forms, but for complex applications, especially large forms, Reactive Forms (covered later) offer more control.