0
0
Angularframework~5 mins

Two-way binding in forms in Angular

Choose your learning style9 modes available
Introduction

Two-way binding lets your form inputs and your app data stay in sync automatically. When you change the input, the data updates, and when the data changes, the input updates.

You want to update a variable as the user types in a text box.
You want to show the current value of a variable inside a form input.
You want to keep form data and your app state connected without writing extra code.
You want to build interactive forms that react instantly to user input.
Syntax
Angular
<input [(ngModel)]="propertyName" />
Use [(ngModel)] inside form elements to bind data both ways.
Make sure to import FormsModule in your module or standalone component's imports array to use ngModel.
Examples
Binds the input value to the username property in your component. Typing updates username, and changing username updates the input.
Angular
<input [(ngModel)]="username" />
Two-way binds a textarea to the description property.
Angular
<textarea [(ngModel)]="description"></textarea>
Two-way binds a dropdown select to selectedOption.
Angular
<select [(ngModel)]="selectedOption">
  <option value="1">One</option>
  <option value="2">Two</option>
</select>
Sample Program

This component shows a text input bound to the name property. When you type your name, the greeting updates instantly 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">Name:</label>
    <input id="nameInput" [(ngModel)]="name" aria-label="Name input" />
    <p>Hello, {{ name }}!</p>
  `
})
export class TwoWayBindingComponent {
  name = '';
}
OutputSuccess
Important Notes

Always import FormsModule in your module or standalone component's imports array to use ngModel.

Use aria-label or label elements for accessibility.

Two-way binding is great for simple forms but consider reactive forms for complex validation.

Summary

Two-way binding keeps form inputs and component data in sync automatically.

Use [(ngModel)] to bind input elements to component properties.

Remember to import FormsModule and add accessibility labels.