Two-Way Data Binding in Angular
Two-way data binding in Angular is a key concept that allows your UI (view) and your component (model) to stay in sync. It means when the user updates the input, the model gets updated automatically, and vice versa.
🔁 What is Two-Way Data Binding?
Two-way data binding connects a form input element to a component variable both ways:
- Component → Template (displaying the value)
- Template → Component (updating the value)
✅ Syntax
<input [(ngModel)]="username" />
The [(ngModel)] is shorthand for combining:
<input [ngModel]="username" (ngModelChange)="username = $event" />
📦 Prerequisite
You must import FormsModule in your module to use ngModel.
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [ FormsModule ]
})
export class AppModule { }
✏️ Example
Component (app.component.ts)
export class AppComponent {
username: string = 'AngularDev';
}
Template (app.component.html)
<input [(ngModel)]="username" placeholder="Enter your name" />
<p>Hello, {{ username }}!</p>
Typing in the input updates username in real time and reflects the change immediately.
🔄 Use Case: Toggle a Checkbox
<label>
<input type="checkbox" [(ngModel)]="isSubscribed" />
Subscribe
</label>
<p *ngIf="isSubscribed">Thanks for subscribing!</p>
Comments
Post a Comment