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
- [code language=”typescript”]
- 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() {
- }
- }
- [/code]
Stringinterpolationdemo.component.html
- [code language=”html”]
- <h1>String Interpolation Demo</h1>
- <h2>Number {{number1}}</h2>
- <br/>
- <h2>Name {{name}}</h2>
- <br/>
- <ul>
- <li *ngFor="let i of arr">{{i}}</li>
- </ul>
- [/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
- [code language=”html”]
- 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');
- }
- }
- [/code]
Stringinterpolationdemo.component.html- [code language=”html”]
- <h1>Event Binding</h1>
- <button (click)="onClick()" >Click Me</button>
- [/code]
OutputTwo-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
- [code language=”html”]
- <h1>Add Two Numbers</h1>
- <input type="number" [(ngModel)]="number1"/><br/>
- <input type="number" [(ngModel)]="number2"/><br/>
- <button (click)="add()"> Add</button>
- <h1>ans is {{ans}}</h1>
- [/code]
addtwonumberdemo.component.ts
- [code language=”typescript”]
- 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;
- }
- }
- [/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
- [code language=”typescript”]
- 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);
- }
- }
- [/code]
addtwonotemplatebinding.component.html
- [code language=”html”]
- <h1>Add Two Numbers Template Binding</h1>
- <input type="number" #number1/><br/>
- <input type="number" #number2/><br/>
- <button (click)="add(number1.value,number2.value)"> Add</button>
- <h1>ans is {{ans}}</h1>
- [/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
- [code language=”typescript”]
- 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() {}
-
- ngOnInit() {}
- onTest() {
- return true;
- }
- }
- [/code]
propertybindingdemo.component.html- [code language=”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>
- [/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.