How to Use ngModel in Angular for Two-Way Data Binding
Use
ngModel in Angular to create two-way data binding between form inputs and component variables. Add [(ngModel)]="propertyName" to an input element and import FormsModule in your module to enable this feature.Syntax
The ngModel directive binds a form input to a component property for two-way data binding. The syntax uses square brackets and parentheses together: [(ngModel)]="propertyName".
propertyName: The component variable to bind.[]: Binds the input value from the component to the view.(): Listens for changes in the input and updates the component.
Remember to import FormsModule in your Angular module to use ngModel.
html
<input [(ngModel)]="propertyName" placeholder="Enter text">
Example
This example shows a text input bound to a component variable name. Typing in the input updates the variable, and the variable's value is displayed below in real time.
typescript
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <h2>Enter your name:</h2> <input [(ngModel)]="name" placeholder="Name"> <p>Hello, {{ name }}!</p> ` }) export class AppComponent { name = ''; } // In app.module.ts, import FormsModule: // import { FormsModule } from '@angular/forms'; // import { BrowserModule } from '@angular/platform-browser'; // import { NgModule } from '@angular/core'; // // @NgModule({ // imports: [BrowserModule, FormsModule], // declarations: [AppComponent], // bootstrap: [AppComponent] // }) // export class AppModule {}
Output
Enter your name:
[input box]
Hello, [typed name]!
Common Pitfalls
- Forgetting to import
FormsModulein your module causesngModelto not work. - Using
ngModelwithout the banana-in-a-box syntax[( )]will not create two-way binding. - Binding to a property that is not defined in the component causes errors.
html
/* Wrong: Missing FormsModule import and no two-way binding syntax */ <input ngModel="name"> <!-- This will not work properly --> /* Right: Proper two-way binding with FormsModule imported */ <input [(ngModel)]="name">
Quick Reference
| Feature | Description | Example |
|---|---|---|
| Two-way binding syntax | Bind input and component property both ways | |
| Import requirement | Must import FormsModule in your module | import { FormsModule } from '@angular/forms'; |
| Property binding only | Bind input value from component only | |
| Event binding only | Update component on input change only |
Key Takeaways
Always import FormsModule in your Angular module to use ngModel.
Use [(ngModel)]="property" syntax for two-way data binding.
ngModel keeps input and component property in sync automatically.
Without the banana-in-a-box syntax, ngModel does not bind both ways.
Define the bound property in your component to avoid errors.