Introduction To Data Binding In Angular 2

Data Binding basically means interacting with data. So, we can say that the interaction between templates and business logic is called data binding.

Data binding means communication. It means that the component body /logic and the typescript code interact with the component template (View), and also listen to the events.

Data binding is the most important feature in the software development process. We need Data binding in each and every step, especially where we want to bind some dynamic content/data. So, Angular 2 comes with various data binding options, mentioned below.



To demonstrate all the bindings, I am using Angular 2 CLI project, which you also can download from the download link.

Note- To run the project in your machine, you need to install all the dependencies from package.json. To do so, write " npm install " in your command prompt.
 
String Interpolation

It is the easiest way of displaying dynamic data to the View. In String Interpolation method, we just need to pass the property name enclosed within the {{ name of the property }}.

In the below example, I have defined two properties, named as number1 (number type) and string (string type). One array type of string will be displaying these properties of the class on to View, by using String Interpolation .

Stringinterpolationdemo.component.ts

  1. [code language=”typescript”]  
  2.    import { Component, OnInit } from '@angular/core';  
  3.    @Component({  
  4.       selector: 'app-stringinterpolationdemo',  
  5.       templateUrl: './stringinterpolationdemo.component.html',  
  6.       styleUrls: ['./stringinterpolationdemo.component.css']  
  7.       })  
  8.    export class StringinterpolationdemoComponent implements OnInit {  
  9.       number1:number=10;  
  10.       name:string='jinal shah';  
  11.       arr:string[]=['India','Usa','Uk','Japan'];  
  12.       constructor() { }  
  13.       ngOnInit() {  
  14.       }  
  15.    }  
  16. [/code]  
Stringinterpolationdemo.component.html
  1. [code language=”html”]  
  2. <h1>String Interpolation Demo</h1>  
  3.    <h2>Number {{number1}}</h2>  
  4.       <br/>  
  5.    <h2>Name {{name}}</h2>  
  6.       <br/>  
  7.    <ul>  
  8.       <li *ngFor="let i of arr">{{i}}</li>  
  9.    </ul>  
  10. [/code]  
Output



Event Binding

Angular 2 uses HTML elements events directly. For that, we just need to write the name of the Event enclosed within the ().

In the below example, I have created a simple click event for the button.

Stringinterpolationdemo.component.ts
  1. [code language=”html”]  
  2. import { Component, OnInit } from '@angular/core';  
  3. @Component({  
  4.          selector: 'app-stringinterpolationdemo',  
  5.          templateUrl: './stringinterpolationdemo.component.html',  
  6.          styleUrls: ['./stringinterpolationdemo.component.css']  
  7.          })  
  8. export class StringinterpolationdemoComponent implements OnInit {  
  9.       constructor() { }  
  10.       ngOnInit() {  
  11.       }  
  12.       onClick(){  
  13.       alert('Hello world');  
  14.       }  
  15.    }  
  16. [/code]  
Stringinterpolationdemo.component.html
  1. [code language=”html”]  
  2.    <h1>Event Binding</h1>  
  3.    <button (click)="onClick()" >Click Me</button>  
  4. [/code]  
Output



Two-Way Binding

Two-way binding made Angular JS 1.x more famous. We can achieve two-way binding with the help of $scope object of Angular JS 1.x but in Angular 2, the by default behavior of two-way binding is removed to improve the performance. But, we can achieve two-way binding in Angular2 by using ngModel. It uses both the syntax of property binding and the event binding [(ngModel)] because two-way binding is a combination of both, property and event binding.

In the below example, I have created one small demo for adding two numbers.

addtwonumberdemo.component.html
  1. [code language=”html”]  
  2. <h1>Add Two Numbers</h1>  
  3.    <input type="number" [(ngModel)]="number1"/><br/>  
  4.    <input type="number" [(ngModel)]="number2"/><br/>  
  5.    <button (click)="add()"> Add</button>  
  6. <h1>ans is {{ans}}</h1>   
  7. [/code]  
addtwonumberdemo.component.ts
  1. [code language=”typescript”]  
  2. import { Component, OnInit } from '@angular/core';  
  3.    @Component({  
  4.             selector: 'app-addtwonumberdemo',  
  5.             templateUrl: './addtwonumberdemo.component.html',  
  6.             styleUrls: ['./addtwonumberdemo.component.css']  
  7.             })  
  8.       export class AddtwonumberdemoComponent implements OnInit {  
  9.             number1:number=0;  
  10.             number2:number=0;  
  11.             ans:number=0;  
  12.             constructor() { }  
  13.             ngOnInit() {  
  14.             }  
  15.       add(){  
  16.             this.ans=this.number1+this.number2;  
  17.             }  
  18.          }  
  19. [/code]  
Output



So, here in the above example, I am using two-way binding. You guys might be wondering how I am able to fetch the value of input box in my TypeScript class!! Well, it is all because of two-way binding. As the name suggests, it is two-way. If I change the value of input box, it will detect each and every change on component and update the property of number1 to new value and if I change the value of property number1 from TypeScript class, it will also update the value of input box.

Template Binding

You might be wondering if two-way binding is that effective, then why is it removed from Angular 2 by default. Well, the answer is here - By removing the two-way binding, they have easily improved the performance of Angular2 because two-way binding detects each and every change on the template, which degrades the performance.

So, what is Template Binding? We can achieve the same thing that we can achieve using two-way binding, by simply using Template Binding. Angular2 comes with a new feature which allows us the direct access of HTML element. We can get the value of the element by simply creating template reference variable. We can create template reference variable by preceding the # symbol.

So, here is the same example of adding two numbers using template binding.

addtwonotemplatebinding.component.ts
  1. [code language=”typescript”]  
  2. import {  
  3.     Component,  
  4.     OnInit  
  5. } from '@angular/core';  
  6. @Component({  
  7.     selector: 'app-addtwonotemplatebinding',  
  8.     templateUrl: './addtwonotemplatebinding.component.html',  
  9.     styleUrls: ['./addtwonotemplatebinding.component.css']  
  10. })  
  11. export class AddtwonotemplatebindingComponent implements OnInit {  
  12.     ans: number = 0;  
  13.     constructor() {}  
  14.     ngOnInit() {}  
  15.     add(no1, no2) {  
  16.         this.ans = parseInt(no1) + parseInt(no2);  
  17.     }  
  18. }  
  19. [/code]  
addtwonotemplatebinding.component.html
  1. [code language=”html”]  
  2. <h1>Add Two Numbers Template Binding</h1>  
  3.       <input type="number" #number1/><br/>  
  4.       <input type="number" #number2/><br/>  
  5.       <button (click)="add(number1.value,number2.value)"> Add</button>  
  6. <h1>ans is {{ans}}</h1>  
  7. [/code]  
Property Binding

In Angular 2, we can access the html element property directly. To achieve property binding, we can simply use [].

Here are the examples of property binding.

propertybindingdemo.component.ts
  1. [code language=”typescript”]  
  2. import {  
  3.     Component,  
  4.     OnInit  
  5. } from '@angular/core';  
  6. @Component({  
  7.     selector: 'app-propertybindingdemo',  
  8.     templateUrl: './propertybindingdemo.component.html',  
  9.     styleUrls: ['./propertybindingdemo.component.css']  
  10. })  
  11. export class PropertybindingdemoComponent implements OnInit {  
  12.     name: string = ’jinal shah’;  
  13.     constructor() {}  
  14.   
  15.     ngOnInit() {}  
  16.     onTest() {  
  17.         return true;  
  18.     }  
  19. }  
  20. [/code]  
propertybindingdemo.component.html
  1. [code language=”html”]  
  2. <h1>Property Binding Demo</h1>  
  3. <input type="text" [value]="name"/>  
  4. <p [ngClass]="{redborder: onTest()}">is it styled?</p>  
  5. <p [ngStyle]="{color:'blue'}">Text Color</p>  
  6. [/code]  
Output



Conclusion

By reading this article, one would get the complete idea about how data binding works in Angular 2. Thanks for reading it and hope it will be useful to you guys.