One-Way And Two-Way Data Binding With Examples In Angular

 Brief of Data Binding 

  • In Angular 2, Data Binding is mainly classified in two ways - one-way binding (i.e. unidirectional binding) and two-way binding (i.e. bi-directional binding).
  • In simple words, if you compare this with MVC applications, it is similar to the process of how we synchronize the data between the View to Model and Model to View.

Classification of Data Binding

Angular

In the below sections, we will see both the concepts one by one with examples.

One-way Data Binding: [Component to View]

It will bind the data from Component to View using the following different ways.

Different types of one-way data binding.

  • Interpolation Binding
  • Property Binding
  • Attribute Binding
  • Class Binding
  • Style Binding

Interpolation Binding

  • With interpolation, we place the component property name in the View template, enclosed in double curly braces: {{property Name}}. 
  • In simple words, interpolation is nothing but how we use this binding expression {{}} in our project. We will see that with an example.

Simple Example

File Name: Index.html [start up page is used for all components]

  1. <!DOCTYPE html>  
  2. <html> e
  3.   <head>  
  4.     <title>First Angular Program</title>  
  5.     <base href="/src/">  
  6.     <meta charset="UTF-8">  
  7.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  8.     <link rel="stylesheet" href="styles.css">  
  9.   
  10.     <!-- Polyfill(s) for older browsers -->  
  11.     <script src="/node_modules/core-js/client/shim.min.js"></script>  
  12.   
  13.     <script src="/node_modules/zone.js/dist/zone.js"></script>  
  14.     <script src="/node_modules/systemjs/dist/system.src.js"></script>  
  15.   
  16.     <script src="systemjs.config.js"></script>  
  17.     <script>  
  18.       System.import('main.js').catch(function(err){ console.error(err); });  
  19.     </script>  
  20.   </head>  
  21.   
  22.   <body>   
  23.   
  24.       <!--Here is the selector mapped-->  
  25.       <my-app>Loading AppComponent content here ...</my-app>  
  26.        
  27.   </body>  
  28. </html>

File Name: app.component.ts

  1. import { Component } from "@angular/core";  
  2. @Component({  
  3.     selector: 'my-App',  
  4.     template: `  
  5.                 <div>  
  6.                 <strong>{{firstname}}</strong>  
  7.                  <strong>{{lastname}}</strong>  
  8.                 </div>  
  9. })  
  10. export class AppComponent {  
  11.     firstname: string = "Sachin";  
  12.     lastname:string = "Tendulkar"  

Output

Angular

Property Binding
  • It is used to bind values of component/model properties to the HTML element.
  • Depending on the values, it will change the existing behavior of the HTML element.

Syntax

[property] =’expression’

In property binding, there is source and target. For this example, we can define it as [innerHTML] = 'firstname'. Here, innerHTML is a target that is a property of span tag and source is a component property i.e. firstname. 

Example

  1. import { Component } from "@angular/core";  
  2.   
  3. @Component({  
  4.   
  5.     selector: 'my-App',  
  6.     template: `  
  7.                 <div>  
  8.                 <span [innerHTML]='firstname'></span>                  
  9.                 </div>  
  10. })  
  11. export class AppComponent {  
  12.     firstname: string = "Sachin";  
  13. }

Output

Angular

Attribute Binding
  • With attribute binding, we can set the value of an attribute directly. The thing to note is that you must use the attribute binding only when there is no element property there to bind.
  • For example, here are the elements which don’t have the property => ARIASVG, and table span attributes.

Example

  1. <table border="1">  
  2.     <thead>  
  3.         <tr>  
  4.             <th [attr.colspan]="2">Student Details</th>  
  5.             
  6.         </tr>  
  7.     </thead>  
  8.     <tbody>  
  9.         <tr>  
  10.             <td>First Name</td>  
  11.             <td>{{firstName}}</td>  
  12.         </tr>  
  13.         <tr>  
  14.             <td>Last Name</td>  
  15.             <td>{{lastName}}</td>  
  16.         </tr>  
  17.         <tr>  
  18.             <td>Gender</td>  
  19.             <td>{{gender}}</td>  
  20.         </tr>  
  21.         <tr>  
  22.             <td>Qualification</td>  
  23.             <td>{{qualification}}</td>  
  24.         </tr>  
  25.     </tbody>  
  26. </table> 

Output

Angular
Negative Test for Attribute Binding

For curiosity, we will check what will be the error if we use interpolation or property binding in the "colspan" attribute. Here is the output.

Ex

Interpolation for colspan :<th colspan={{2}}>Student Details</th>

Error

Template parse errors: Can't bind to 'colspan' since it isn't a known native property

Angular

Property binding for colspan: <th [colspan]="2">Student Details</th>

Angular

Class Binding

  • By using the class binding, we can add and remove CSS class names from HTML elements
  • It is similar to the attribute binding but it starts with the prefix class, optionally followed by a dot (.) and the name of a CSS class: [class. Class-name]

Example of adding a class

  1. <style>  
  2.     .txtcenter{  
  3.     text-align:center;  
  4. }  
  5.   
  6. .txtright{  
  7.      text-align:right;  
  8. }  
  9.   
  10. .txtleft{  
  11.       text-align:left;  
  12. }  
  13. </style>  
  14.   
  15. <table border="1">  
  16.     <thead>  
  17.         <tr>  
  18.             <th [attr.colspan]="2" class="txtcenter"  [class.txtright]='true'>Student Details</th>  
  19.             
  20.         </tr>  
  21.     </thead>  
  22.     <tbody>  
  23.         <tr>  
  24.             <td>First Name</td>  
  25.             <td>{{firstName}}</td>  
  26.         </tr>  
  27.         <tr>  
  28.             <td>Last Name</td>  
  29.             <td>{{lastName}}</td>  
  30.         </tr>  
  31.         <tr>  
  32.             <td>Gender</td>  
  33.             <td>{{gender}}</td>  
  34.         </tr>  
  35.         <tr>  
  36.             <td>Qualification</td>  
  37.             <td>{{qualification}}</td>  
  38.         </tr>  
  39.     </tbody>  
  40. </table>  

In the above code, [class.txtright]='true' added the class txtright for the <th> element.

Output

Angular
Style Binding

By using the style binding, we can set inline styles to the HTML element.

One important point here is that it is used to set single line style. If you want to send multiple line style, then Angular provides a good attribute directive called NgStyle.

Syntax

It is similar to the attribute and class binding. It also starts with the prefix style, followed by a dot (.) and the name of a CSS style property: [style. Style-property].

Example

  1. <thead>  
  2.         <tr>  
  3.             <th [attr.colspan]="2"  [style.font-size.px]="50">Student Details</th>  
  4.             
  5.         </tr>  
  6.     </thead>  

Output

Angular

Note

This brings us to the end of the first way (Component to View) of one-way data binding. Given below is the second way (View to Component) One-way data binding.

One way Data-Binding [View to Component]

Event Binding

Event binding flows or binds the data from an HTML element to a component.

Syntax

Within parentheses on the left of the equal sign, we have the target event ("click" in this case) and on the right side, we have the template statements such as component properties and methods.

  1. <button (click)="onClick()">Click me</button>  

In this case, the onClick() method of the component class is called when the click event occurs.

Example

File name app.component.ts

  1. import { Component } from "@angular/core";  
  2.   
  3. @Component({  
  4.   
  5.     selector: 'my-App',  
  6.     template: `<button (click)='onClick()' >Click me</button>`  
  7.   
  8. })  
  9.   
  10. export class AppComponent {  
  11.     onClick(): void {  
  12.         console.log('you clicked me!!');  
  13.     }  
  14. }  

Output

Angular

Note - The above example can also be written using the canonical for syntax like below.

Same syntax can be done using canonical form

An event binding using on- keyword is achieved as follows.

  1. <button on-click="onClick()">Click me</button>  

Two-way Data Binding

  • In simple words, two-way data binding is a combination of both Property Binding and Event Binding.
    1. <input [value]='data1' (input)='data1 = $event.target.value'
  • That is, it provides the bi-directional synchronization between the View and the Component.

Example

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     selector: 'my-app',  
  5.     template: `  
  6.                 Enter the value  : <input [value]='data1' (input)='data1 = $event.target.value'>  
  7.                 <br>  
  8.                  Entered value : Hi  {{data1}}  
  9.               `  
  10. })  
  11. export class AppComponent {  
  12.     data1: string = '';  
  13. }  

Output

Angular

Binding using [(ngModel)] directive

To simplify the above example, Angular 2 provides the ngModel directive which combines the square brackets of property binding with the parentheses of event binding in a single notation.

Syntax

  1. <input [(ngModel)] =’data1’>  

Prerequisite Important Note

When you are using NgModule directive, make sure you have imported Angular system Module called Form Module in app.module.ts file like below.

Filename app.module.ts

  1. import { FormsModule } from "@angular/forms"  
  2.   
  3. import { NgModule } from '@angular/core';  
  4. import { BrowserModule } from '@angular/platform-browser';  
  5. import { FormsModule } from "@angular/forms"  
  6.   
  7. import { AppComponent } from './app.component';  
  8.   
  9. @NgModule({  
  10.     imports: [BrowserModule, FormsModule],  
  11.     declarations: [ AppComponent],  
  12.     bootstrap: [AppComponent]  
  13. })  
  14. export class AppModule { }  

Otherwise, you will get the below error in browser console.

Template parse errors

Can't bind to 'ngModel' since it isn't a known property of 'input'.

After importing, below is the example which is presented in File Name: app.component.ts 

Example 

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     selector: 'my-app',  
  5.     template: `  
  6.                 Enter the value  : <input [(ngModel)] ='data1'>  
  7.                 <br>  
  8.                  Entered value : Hi  {{data1}}  
  9.               `  
  10. })  
  11. export class AppComponent {  
  12.     data1: string = '';  
  13. }  

Output

Angular

Conclusion

In Angular 2, Data Binding is a very good and useful feature, which can be easily implemented in our projects.

Hope, the above information was helpful. Kindly share your thoughts or feedbacks. And, if you like to explore more Angular concepts, here are the links.

Up Next
    Ebook Download
    View all
    Learn
    View all