Introduction to Data Bindings in Angular2

Data Binding is basically means interacting with data and interaction between templates and business logic.

screenshot-101

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

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

screenshot-102

To demonstrate all the bindings I am using angular 2 CLI project. Which you can also download from the download link.(Note: To run project in your machine you must need to install all the dependency from package.json to do so you must write npm install in your command prompt)

  • String Interpolation :

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

In Below example ,I had defined two property named as number1 is type of number and name is type of string and one array type of string will be displaying this all property of class on to view by using String Interpolation .

 

Stringinterpolationdemo.component.ts


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

@Component({

 selector: 'app-stringinterpolationdemo',

 templateUrl: './stringinterpolationdemo.component.html',

 styleUrls: ['./stringinterpolationdemo.component.css']

})

export class StringinterpolationdemoComponent implements OnInit {

number1:number=10;

name:string='jinal shah';

arr:string[]=['India','Usa','Uk','Japan'];

 constructor() { }

 ngOnInit() {

 }

}

Stringinterpolationdemo.component.html

<h1>String Interpolation Demo</h1>
<h2>Number {{number1}}</h2>
<h2>Name {{name}}</h2>
<ul>
	<li *ngFor="let i of arr">{{i}}</li>
</ul>

Output:

op1

  • 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 below example I had created simple click event for button.

stringinterpolationdemo.component.ts


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

@Component({

 selector: 'app-stringinterpolationdemo',

 templateUrl: './stringinterpolationdemo.component.html',

 styleUrls: ['./stringinterpolationdemo.component.css']

})

export class StringinterpolationdemoComponent implements OnInit {

constructor() { }

 ngOnInit() {

 }

onClick(){

 alert('Hello world');

}

}

stringinterpolationdemo.component.html

<h1>Event Binding</h1>
<button (click)="onClick()" >Click Me</button>

Output:

op2

  • Two-Way Binding:

Two-way binding made angular js 1.x more famous .we can achieve two-way binding with 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 ngModel. It uses both syntax of property binding and event binding  [(ngModel)] because two-way binding is a combination of both property and event binding.

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

addtwonumberdemo.component.html

<h1>Add Two Numbers</h1>
<input type="number" [(ngModel)]="number1"/>

<input type="number" [(ngModel)]="number2"/>

<button (click)="add()"> Add</button>
<h1>ans is {{ans}}</h1>

addtwonumberdemo.component.ts


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

@Component({

selector: 'app-addtwonumberdemo',

templateUrl: './addtwonumberdemo.component.html',

styleUrls: ['./addtwonumberdemo.component.css']

})

export class AddtwonumberdemoComponent implements OnInit {

number1:number=0;

number2:number=0;

ans:number=0;

constructor() { }

ngOnInit() {

}

add(){

this.ans=this.number1+this.number2;

}

}

Output:

op3

So here in above example I am using two-way binding, you guys might be wondering how I can able to fetch the value of input box in my typescript class!! Well it is all because of two-way binding ,As the name suggest it is two-way (i.e. if i change 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 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 much effective then why it is removed from Angular 2 by default? Well the answer is here: by removing the two-way binding they can easily improve the performance of angular2 because two-way binding detects each and every change on template and that will degrade the performance.

Now what is template binding? Well we can achieve the same thing what we can achieve using two-way binding by simply using template binding. Angular2 comes with the new feature which will allow us to direct access of html element. We can get the value of element by simple 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


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

@Component({

selector: 'app-addtwonotemplatebinding',

templateUrl: './addtwonotemplatebinding.component.html',

styleUrls: ['./addtwonotemplatebinding.component.css']

})

export class AddtwonotemplatebindingComponent implements OnInit {

ans:number=0;

constructor() { }

ngOnInit() {

}

add(no1,no2){

this.ans= parseInt(no1)+parseInt(no2);

}

}

addtwonotemplatebinding.component.html

<h1>Add Two Numbers Template Binding</h1>
<input type="number" #number1/>

<input type="number" #number2/>

<button (click)="add(number1.value,number2.value)"> Add</button>
<h1>ans is {{ans}}</h1>
  • Property Binding:

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

          Here are the few example of property bindings.

    propertybindingdemo.component.ts


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

@Component({

selector: 'app-propertybindingdemo',

templateUrl: './propertybindingdemo.component.html',

styleUrls: ['./propertybindingdemo.component.css']

})

export class PropertybindingdemoComponent implements OnInit {

name:string=’jinal shah’;

constructor() { }

&nbsp;

ngOnInit() {

}

onTest(){

return true;

}

}

  propertybindingdemo.component.html

<h1>Property Binding Demo</h1>
<input type="text" [value]="name"/>
<p [ngClass]="{redborder: onTest()}">is it styled?</p>
<p [ngStyle]="{color:'blue'}">Text Color</p>


propertybindingdemo.component.css


.redborder{
border: 1px solid red;
}

Output:

op4

Conclusion:

By reading this article one can get the complete idea about the how data binding works in angular 2.

Thanks for reading it and hope it will be useful to you guys.

Advertisements

2 thoughts on “Introduction to Data Bindings in Angular2”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s