AngularJS 2.0 From The Beginning - Data Binding - Day Three

I am here to continue the discussion around AngularJS 2.0. Today, we will discuss Data Binding in AngularJS 2. Also, in case you did not have a look at our previous articles of this series, go through the links, mentioned below. 

In my previous article, I already discussed about the life cycle of the component. Now in this article, I will discuss about one of the main advantages of the Angular framework i.e. data binding. As per our previous experience regarding Angular 1.x series, data binding is one key feature which makes our development very easy with less coding for capturing or binding the data within the view interface. In Angular 1.x, data binding provides us two different mechanisms for binding the data; i.e., one-way binding and two-way binding.

Now, in Angular 2.0, there are couple of ways we can use for the data binding concept. They are,

  1. Interpolation
  2. Property Binding
  3. Two Way Binding
  4. Event Binding

Interpolation

Interpolation data binding is the most popular and easiest way of data binding in AngularJS. This mechanism is also available in earlier versions of the Angular framework. Actually, context between the braces is the template expression that AngularJS first evaluates and then converts into strings. Interpolation uses the braces expression i.e. {{ }} for rendering the bound value to the component template. It can be a static string or numeric value or an object of your data model.

As per our example, in AngularJS, we use it like below.

{{model.firstName}}

Here, model is the instance of the Controller objects. But in Angular 2, it is now much simpler where Controller instance name is removed from the expression, i.e.

{{firstName}}

Property Binding

In AngularJS 2.0, a new binding mechanism is introduced, called Property Binding. But actually in nature, it is just same as interpolation or one-way binding. Some people call this process one way binding just like in the previous AngularJS concept. Property binding uses [ ] to send the data from the component to the HTML template. The most common way to use property binding is to assign any property of the HTML element tag into the [ ], with component property value, i.e.

<input type=”text” [value]=”data.name”/>

In the previous version of AngularJS, it could be done by using ng-bind directives. Basically, property binding can be used to bind any property, component, or a directive property. It can be used as

  • Attribute binding
  • Class binding
  • Style binding

Now, for demonstrating the interpolation and one-way binding, we first create an interpolation component. For doing this, we need to do the following.

Step 1

Create one TypeScript file named as app.component.interpolation.ts and add the below code.
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'interpolation',  
  6.     templateUrl: 'app.component.interpolation.html'  
  7. })  
  8.   
  9. export class InterpolationComponent {  
  10.     value1: number = 10;  
  11.     array1: Array<number> = [10, 22, 14];  
  12.     dt1: Date = new Date();  
  13.   
  14.     status: boolean = true;  
  15.   
  16.     returnString() {  
  17.         return "String return from function";  
  18.     }  

Step 2

Now, add another HTML file named app.component.interpolation.html and add the below code.
  1. <div>  
  2.     <span>Current Number is {{value1}}</span>  
  3.     <input [value]="value1" />  
  4.     <span>Status is {{status}}</span>  
  5.     <br /><br />  
  6.     <span>{{status ? "This is correct status" :"This is false status"}}</span>  
  7.     <br /><br />  
  8.     <span>{{returnString()}}</span>  
  9. </div> 
Step 3

Create another TypeScript file named as app.component.parent.ts and add the below code.
  1. import { Component, OnInit } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'my-app',  
  6.     templateUrl: 'app.component.parent.html',  
  7. })  
  8.   
  9. export class ParentComponent implements OnInit {  
  10.     constructor() { }  
  11.   
  12.     ngOnInit() { }  

Step 4

Again, create an HTML file named app.component.parent.html and add the below code. 
  1. <div>  
  2.     <h2>Demonstration of Interpolation</h2>  
  3.     <interpolation></interpolation>  
  4. </div> 
Step 5

Lastly, create another TypeScript file named app.module.ts and add the below code.
  1. import { NgModule } from '@angular/core';  
  2. import { FormsModule } from '@angular/forms';  
  3. import { BrowserModule } from '@angular/platform-browser';  
  4. import { ParentComponent } from './src/app.component.parent';  
  5. import { InterpolationComponent } from './src/app.component.interpolation';  
  6.   
  7. @NgModule({  
  8.     imports: [BrowserModule, FormsModule],  
  9.     declarations: [ParentComponent, InterpolationComponent],  
  10.     bootstrap: [ParentComponent]  
  11. })  
  12. export class AppModule { } 
Now, run the code. The output is shown below.

 
Event Binding

Event Binding is one of the new mechanisms introduced by AngularJS 2.0 an a new concept. In previous versions of AngularJS, we always used different types of directives like ng-click, ng-blur, for binding any particular event action of an HTML control. But in Angular 2, we need to use the same property of the HTML element (like click, change etc.) and use it within parentheses. So, in Angular 2, with properties, we use square brackets and in events, we use parentheses.

<button (click)=”showAlert();”>Click</button>

For doing this, add another TypeScript file named app.component.eventbinding.ts and add the below code.
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'event-bind',  
  6.     templateUrl: 'app.component.eventbinding.html'  
  7. })  
  8.   
  9. export class EventBindingComponent {  
  10.     showAlert() {  
  11.         console.log('You clicked on the button...');  
  12.         alert("Click Event Fired...");  
  13.     }  

Now, add another HTML file named app.component.eventbinding.html and add the below code.
  1. <div>  
  2.     <input type="button" value="Click" class="btn-block" (click)="showAlert()" />  
  3.     <br /><br />  
  4.     <input type="button" value="Mouse Enter" class="btn-block" (mouseenter)="showAlert()" />  
  5. </div> 
Place the <event-bind> selector in the parent HTML and add the component name in the module. Now, run the code. The output is shown below -
 
Two Way Binding

The most popular and widely used data binding mechanism is two-way binding in the Angular framework. Basically, two-way binding is used in the input type field or any form elements where user type or change of any Control value is done in the one side, and on the other side, the same is automatically updated into the Controller variables and vice versa. In Angular 1.x, we used ng-model directives with the element for this purpose.

<input type=”text” ng-model =”firstName”/>

Similarly, in Angular 2.0, we have a directive called ngModel and it can be used as below.

<input type=”text” [(ngModel)] =”firstName”/>

As we see, in Angular 2, the syntax is different because we use [ ] - since it is actually a property binding and parentheses are used for the event binding concept.

What is ngModel

As I already said in the previous section of the article, ngModel basically performs both property binding as well as event binding. Actually, property binding of ngModel (i.e. [ngModel]) performs the activity to update the input element with value, whereas (ngModel) (basically, fired in the (ngModelChange) event) instructs the outside world when any changes have occurred in the DOM Element.

For demonstrating two-way binding, add another TypeScript file named app.component.twowaybind.ts and add the below code.
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'twowaybind',  
  6.     templateUrl: 'app.component.twowaybind.html'  
  7. })  
  8.   
  9. export class TwoWayBindComponent {  
  10.     val: string = "";  

Now add another HTML file named app.component.twowaybind.html and add the below code.
  1. <div>  
  2.     <input [(ngModel)]="val" type="text"/>  
  3.     <span>{{val}}</span>  
  4.     <br />  
  5.     <input [value]="val" (keyup)="num = $event.target.value" />  
  6. </div>  
Now, place the <twowaybind> selector in the parent HTML and add the component name in the module. And then, run the code. The output is as below.