Two way data binding

  • To understand Two way binding we will first create a sample project using angular CLI
  • Then we need to add FormsModule in the app.module.ts file to enable the ngForm directive in our template/html.
  • We need to add name attribute for all the form elements on which two way data binding has to be made, without the name attribute the two way data binding does not work
  • After making changes to app.module.ts file, the file will have details.
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';

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

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

We need to modify app.component.html as below

<p>Enter the text below</p>
**** Line 1 ****One way Event Binding : <input type="text" (input)="onTextInput($event)"/><br/><br/>
**** Line 2 ****<b>Two Way Binding</b> : <input type="text" [(ngModel)]="textMsg"/><br/><br/>
**** Line 3 ****String Interpolation The text entered in the textbox is : {{textMsg}}

We need to modify app.component.ts file as below

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  textMsg : string;
  onTextInput(event : Event){
    this.textMsg = (event.target as HTMLInputElement).value;
  }
}

The output after making all the changes looks like below

  • Line1 Textbox, Line2 Textbox and Line3 String linked to the same property textMsg in our TypeScript
  • Now on Line1 we have used one way event binding i.e on each keypress in the textbox of line1 the value is passed through the method onTextInput() and stored in the textMsg property defined in our TypeScript code.
    • As we change the textbox value on Line 1, the textbox value of Line2 and String on line3 change since line2 textbox and line3 string are binded with the property textMsg
  • Now on Line2 we have used two way binding i.e on each keypress in the textbox of lin2 the value is passed through to the textMsg property of TypeScript class AppComponent implicitly using ngForm directive.
    • Hence as we change the value on line2 textbox the value of String on Line3 change accordingly since we are reading the value of the textMsg property on Line3.
  • Thus we can conclude that
    • line1 textbox only write the value to textMsg property but not read because of one way binding
    • line2 textbox can read and write the value from and to textMsg property because of two way binding
    • line3 string can only read the value from textMsg property since it is displayed using StringInterpolation.

Leave a Comment