Overview Of Data And Event Binding In Angular 2 - Day Three

Data binding is a process of communication that is performed between our components (business logic) and View. We pass data from component to View and listen to events from View to component.

In Angular 2, we follow these methods for data binding.

  • String Interpolation
  • Property Binding
  • Event Binding
  • Two Way Binding

Now, learn each method with some examples.

String Interpolations:

In string interpolation method, we bind the value or properties from component to template (View) using double curly braces({{}}). Let’s take an example.

Add the following data in your component app.component.ts file or you can have another component. 

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: '[app-root]',  
  5.   templateUrl: './app.component.html',  
  6.   styleUrls: ['./app.component.css']  
  7. })  
  8.   
  9.   
  10. export class AppComponent {  
  11.   name = 'Pankaj Kumar Choudhary';  
  12.   city = "Alwar";  
  13.   technology=[  
  14.   {name:"Asp.NET MVC", experience:"1 Years"},  
  15.   {name:"Android", experience:"1 Years"},  
  16.   {name:"Ionic", experience:"6 Months"},  
  17.   {name:"Angular", experience:"1 Years"},  
  18.   {name:"Node.js", experience:"6 Months"}  
  19.   ];  
  20.   
  21. }   

In this component, we create an array that contains some objects with two properties (name and experience). Now, go to template page of this component and add the below code.

  1. <h3>  
  2.    My Name is {{name}} <br/>  
  3.     I live in {{city}}  
  4. </h3>  
  5.   
  6. <h3>I am working on these technologies</h3>  
  7.   
  8. <table>  
  9.     <tr><th>Technology</th><th>Experiences</th></tr>  
  10.     <tr *ngFor="let data of technology">  
  11.         <th>{{data.name}}</th><th>{{data.experience}}</th>  
  12.     </tr>  
  13. </table>   

In this example, we are using the string interpolation and showing data using the double curly braces({{}}). When you save this code and refresh the browser, you get the following result.

Output


Property Binding

In property binding, we evaluate some expression to get the desired result and then take some decision on the behalf of this result.

In Angular, we have two types of the property binding.

  • DOM Properties for example <img src=””/>
  • Directive Properties for example <div [ngClass]=”” />

Angular can perform custom properties binding and we will learn about this also. Let’s take an example of property binding. Now, add the below code in “app.component.html” template. 

  1. <h3>  
  2. My Name is {{name}} <br/>  
  3.  I live in {{city}}  
  4. </h3>  
  5.   
  6. <h3>I am working on these technologies</h3>  
  7.   
  8. <table>  
  9.     <tr><th>Technology</th><th>Experiences</th></tr>  
  10.     <tr *ngFor="let data of technology">  
  11.         <th>{{data.name}}</th><th>{{data.experience}}</th>  
  12.     </tr>  
  13. </table>  
  14.   
  15.   
  16. <div [ngClass]="'customStyle'">  
  17.   
  18. Name:    <input type="text" [ngStyle]="{color:'red'}"  [value]="name" />  
  19. </div>   

In the above code, we are using the DOM and directive property binding. We used “ngStyle” DOM property binding to bind the class style for the div. The code of “customStyle” is shown below.


Now, refresh your browser and you will get the following output.


Custom Property

In Angular 2, now, we can create custom property by defining “@Input” before any property. When we define “@Input” before any property, that means we add edit the value of that property outside the component.

We created another component as “lifey-cycle”. In this component, we define a custom property “newPropety” and assign some value as below.


Template file for this component is,


In this template, we are displaying the value of this property (newProperty). Now, we will use “app-lifey-cycle” as inner component in “app” component.


In this component, we are assigning a new value to “newProperty” of “lifey” component. When you refresh the browser, you will get the following result.


Now, a question may arise as to why the value of “newProperty” is changed. The reason is that we mark “newProperty” as “@Input” that means we can access and assign a new value to this property outside the component.

Event Binding

Similar to property, we can bind any event and also generate an event Listener for that event. Let’s take an example of event binding. Add the below code in your “app” component’s template file. 

  1. <h3>  
  2. My Name is {{name}} <br/>  
  3.  I live in {{city}}  
  4. </h3>  
  5.   
  6. <h3>I am working on these technologies</h3>  
  7.   
  8. <table>  
  9.     <tr><th>Technology</th><th>Experiences</th></tr>  
  10.     <tr *ngFor="let data of technology">  
  11.         <th>{{data.name}}</th><th>{{data.experience}}</th>  
  12.     </tr>  
  13. </table>  
  14.   
  15.   
  16. <div [ngClass]="'customStyle'">  
  17.   
  18. Name:    <input type="text" [ngStyle]="{color:'red'}"  [value]="name" />  
  19. </div>  
  20.   
  21. <input type="button" (click)="ChangeValue()" value="Change Data"/>  
  22.   
  23. <br/>   

In the above code, we are displaying the value of “name” property and we have also a button. On click event of this button, we are calling “ChangeValue” method. Now, create a “ChangeValue” method in your “app” component. In this method, we are changing the value of “name” property.


Now, when the page loads, we will get the following output.


When we click on “Change Data” button, “Pankaj Kumar Choudhary” will be replaced by “Rahul Choudhary”.


Custom Event

Similar to custom property, we can also generate custom events. Let’s take an example of custom events. First of all, we create all codes and after that, we will explain that code.

Lifey-cycle.components.ts 

  1. import { Component, OnInit,Input,Output,EventEmitter } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-lifey-cycle',  
  5.   templateUrl: './lifey-cycle.component.html',  
  6.   styleUrls: ['./lifey-cycle.component.css']  
  7. })  
  8. export class LifeyCycleComponent  {  
  9.   
  10.   constructor() { }  
  11.  @Input() newPropety:string="This is Custom Property";   
  12.   
  13.  @Output() customEvent=new EventEmitter();  
  14.   emitEvent(){  
  15.     this.customEvent.emit('Event fired');  
  16.   }  
  17.   
  18.    
  19. }   

Now, add the below code in lifey-cycle component’s template file.

Lifey-cycle.component.html 

  1. <p >  
  2.   lifey-cycle works!   
  3. </p>  
  4.    <input type="button" value="Fire Event" (click)="emitEvent()" />  
  5.    Value of Custom Property Is:{{newPropety}}  
  6. <br/>   

App.component.html 

  1. <h3>  
  2.    My Name is {{name}} <br/>  
  3.     I live in {{city}}  
  4. </h3>  
  5.   
  6. <h3>I am working on these technologies</h3>  
  7.   
  8. <table>  
  9.     <tr><th>Technology</th><th>Experiences</th></tr>  
  10.     <tr *ngFor="let data of technology">  
  11.         <th>{{data.name}}</th><th>{{data.experience}}</th>  
  12.     </tr>  
  13. </table>  
  14.   
  15.   
  16. <div [ngClass]="'customStyle'">  
  17.   
  18. Name:    <input type="text" [ngStyle]="{color:'red'}"  [value]="name" />  
  19. </div>  
  20.   
  21. <app-lifey-cycle (customEvent)="ChangeValue($event)"></app-lifey-cycle>  
  22.   
  23. <br/>   

App.component.ts 

  1. import { Component,Input,Output,EventEmitter } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: '[app-root]',  
  5.   templateUrl: './app.component.html',  
  6.   styleUrls: ['./app.component.css']  
  7. })  
  8.   
  9.   
  10. export class AppComponent {  
  11.   name:String = 'Pankaj Kumar Choudhary';  
  12.   city = "Alwar";  
  13.   
  14.   ChangeValue(data:String){  
  15.     this.name=data;  
  16.   }  
  17.   
  18.   technology=[  
  19.   {name:"Asp.NET MVC", experience:"1 Years"},  
  20.   {name:"Android", experience:"1 Years"},  
  21.   {name:"Ionic", experience:"6 Months"},  
  22.   {name:"Angular", experience:"1 Years"},  
  23.   {name:"Node.js", experience:"6 Months"}  
  24.   ];  
  25.   
  26.   
  27. }  

 

In lifey-cycle component, we can create an event emitter using the “@Output”. The ”@output” emitter ensures that we can listen to this event outside the component’s scope.


In template folder of lifey-cycle, we have added a button and on onClick event of this button, we are calling “emitEvent” function. In this function, we can write the code that emits the “customEvent” event.


Now in app.compoent.html” page, we need to add an event listener for “customEvent” event. On invoking of this event, we are calling “ChangeValue” method which contains “event” object. Using the value of “$event”, we can update the value of name property in component section.


 Before the invoking of event, we get the following result.


When we click on “Fire Event” button, we change the value of “name” property and the following result displays.


Two Way Binding

In Angular 1.x , two way data binding was on the most extensive feature but in Angular 2, it is not default binding method because two way data binding is very slow and takes more efforts to manage. Let’s take an example of two way data binding in Angular 2.

App.component.html 

  1. <h3>  
  2.    My Name is {{name}} <br/>  
  3.     I live in {{city}}  
  4. </h3>  
  5.   
  6. <br/>  
  7.   
  8. <input type="text" [(ngModel)]="city" > <br/>  
  9. <input type="text" [(ngModel)]="name" >   

In Angular 2, we perform two way binding using “[(ngModel)]” directive. As we know that if we change the value at View, then it will also change at Model and vice versa.


Conclusion

In this article, we learned about data binding and event binding. We also learned how to create custom event and custom binding. I hope you liked this article.