Open In App

Difference between One-way Binding and Two-way Binding

In this article, we will learn the concept of data binding in Angular. We will also explore its types & examine the differences between one-way binding and two-way binding in angular. 

Data binding is a way to synchronise the data between the model and view components automatically. AngularJS implements data-binding that treats the model as the single-source-of-truth in your application & for all the time, the view is a projection of the model. Unlike React, angular supports two-way binding. In this way, we can make the code more loosely coupled. Data binding can be categorized into 2 types, ie., One-way Binding & Two-way Binding.



One way binding:




import { Component } from "@angular/core";
  
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
})
export class AppComponent {
  title = "Displaying the content with one way binding";
}

 






<h3>Displaying the content without one way binding</h3>
  
<hr />
  
<h3 [textContent]="title"></h3>




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

Output:

Two-way binding:




import { Component } from "@angular/core";
  
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
})
export class AppComponent {
  data = "Ram and Syam";
}




<input [(ngModel)]="data"  type="text">
  
<hr>
  
<h3> Entered data is  {{data}}</h3>

 




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

Output:

Difference between One-way & Two-way Binding

One-way binding 

Two-way binding 

In one-way binding, the flow is one-directional.

In a two-way binding, the flow is two-directional.

This means that the flow of code is from ts file to  Html file.

This means that the flow of code is from ts file to Html file as well as from Html file to ts file.

In order to achieve one-way binding, we used the property binding concept in Angular.

In order to achieve a two-way binding, we will use ngModel or banana in a box syntax.

In property binding, we encapsulate the  variable in html with square brackets( [ ] ).

To make sure the app doesn’t break, we need to import ‘FormsModule’ from ‘@angular/forms’. Using ngModel, we will bind a variable from Html to ts file and from ts file to Html file.


Article Tags :