Two Way Data Binding is the technique where the model and view and interconnected. Any change in model or view can synchronize data between both. Angular supports both One way Data binding and Two Way Data Binding.

For example when we are typing, the input data will update from view (template) to model (class) and will print in next tag at same time. All this happens very fast.

Two Way data binding techniques in angular

  1. without ngModel
  2. with ngModel

Example


$event

Two Way Data binding without ngModel is possible by using event and property binding. $event object return event itself.

$event without function

        <!-- app.component.ts -->
  
export class AppComponent {
  name = '';
}          
        <!-- app.component.html -->
      
<input type="search" (input)="name=$any($event.target).value">

<output>{{name}}</output>

$event with function

        <!-- app.component.ts -->

export class AppComponent {
  name = '';
  updateName(x:Event){
    //this.name=x.target.value;
    this.name=(x.target as HTMLInputElement).value;
  };
}    
        <!-- app.component.html -->
    
<input type="search" (input)="updateName($event)">

<output>{{name}}</output>

ngModel

Two way data binding with ngModel is possible by combining both Property Binding and Event Binding. For Property binding, we use [], for event binding we use (). For two way data binding using ngModel, we use ([]).

Two Way Data Binding

[]

Property Binding

()

Event Binding

=

[()]

Two-Way Data Binding

To use ngModel, first import FormsModule in app.module.ts. After importing FormsModule, declare FormsModule in imports in @NgModule.

import FormsModule

        <!-- app.module.ts -->

  import { NgModule } from '@angular/core';
  import { BrowserModule } from '@angular/platform-browser';
  
  import { AppComponent } from './app.component';
  import { FormsModule } from '@angular/forms';
  
  @NgModule({
    declarations: [
      AppComponent,
    ],
    imports: [
      BrowserModule,
      FormsModule
    ],
    providers: [],
    bootstrap: [AppComponent]
  })
  export class AppModule { }

use ngModel

        <!-- app.component.html --> 
    
<input type="text" [(ngModel)]="name">
        <!-- app.component.ts -->
    
export class AppComponent {
  name = '';
}