0
0
AngularHow-ToBeginner · 3 min read

How to Use ngModel for Form Binding in Angular

Use ngModel in Angular to bind form input elements to component properties for two-way data binding. Add FormsModule to your module imports and use [(ngModel)] on input elements to sync data between the form and the component.
📐

Syntax

The ngModel directive binds the value of an input element to a component property. The syntax [(ngModel)]="propertyName" creates two-way binding, meaning changes in the input update the property and vice versa.

To use ngModel, you must import FormsModule in your Angular module.

typescript
import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    FormsModule
  ]
})
export class AppModule { }

// In template:
<input [(ngModel)]="userName" />
💻

Example

This example shows a simple form input bound to a component property userName. Typing in the input updates the property, and the property value is displayed below.

typescript
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <label for="name">Name:</label>
    <input id="name" name="name" [(ngModel)]="userName" placeholder="Enter your name" />
    <p>Hello, {{ userName }}!</p>
  `
})
export class AppComponent {
  userName = '';
}
Output
Name: [input box] Hello, [typed name]!
⚠️

Common Pitfalls

  • Forgetting to import FormsModule causes ngModel to not work and Angular to throw errors.
  • Using [(ngModel)] without a name attribute inside a form can cause issues; always add name for form controls.
  • Trying to use ngModel in reactive forms instead of template-driven forms is incorrect; use FormControl for reactive forms.
typescript
/* Wrong: Missing FormsModule import */
// app.module.ts
@NgModule({
  imports: []
})
export class AppModule { }

/* Right: Import FormsModule */
import { FormsModule } from '@angular/forms';
@NgModule({
  imports: [FormsModule]
})
export class AppModule { }
📊

Quick Reference

Steps to use ngModel:

  • Import FormsModule in your module.
  • Use [(ngModel)]="propertyName" on input elements.
  • Bind the property in your component class.
  • For form controls inside <form>, add a unique name attribute.

Key Takeaways

Always import FormsModule to use ngModel in Angular templates.
Use [(ngModel)] for two-way binding between input elements and component properties.
Add a name attribute to form controls when using ngModel inside forms.
ngModel is for template-driven forms; use reactive forms APIs for reactive forms.
Two-way binding keeps the UI and data model in sync automatically.