DEV Community

Cover image for Two-Way Binding in Angular: Magic Mirror for Your Data
Kavindu Karunasena
Kavindu Karunasena

Posted on

Two-Way Binding in Angular: Magic Mirror for Your Data

Ever-Synced Data

Imagine your UI reflecting changes like a magic mirror. That’s two-way data binding in Angular! It keeps your view (UI) and component data (model) constantly in sync.

Steps to Two-Way Magic

1. Import FormsModule: Include it in your module (@NgModule({ imports: [FormsModule] })) for form-related directives.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; // Import FormsModule for ngModel

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule // Add FormsModule to imports
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Enter fullscreen mode Exit fullscreen mode

2. Use ngModel: Bind the component property to the input value with [(ngModel)]="propertyName" (like a banana in a box!).

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular User';
}
Enter fullscreen mode Exit fullscreen mode
<div>
  <label for="name">Name:</label>
  <input type="text" id="name" [(ngModel)]="name">
</div>
<p>Hello, {{ name }}!</p>
Enter fullscreen mode Exit fullscreen mode

3. Enjoy the Magic! Changes in the input update the property, and vice versa.

Top comments (0)