Data-binding means communication between the TypeScript code of your component and your template which the user sees. Suppose, you have some business logic in your component TypeScript code to fetch some dynamic data from the server and want to display this dynamic data to the user via template because the user sees only the template. Here, we need some kind of binding between your TypeScript code and template (View). This is where data-binding comes into the picture in Angular because it is responsible for this communication.
Data-binding can be either one-way or two-way. Angular provides various types of data binding -
- String Interpolation
- Property Binding
- Event Binding
- Two-way binding
You can download the complete project with data binding examples from here.
Let’s explore these bindings one by one.
String Interpolation
String Interpolation is a one-way data-binding which is used to output the data from a TypeScript code to HTML template (view). It uses the template expression in double curly braces to display the data from the component to the view.
For Example – {{ data }}
I have already created an Angular project using Angular CLI (which is attached to this article). We will use this same project for all future articles.
app.component.ts
- import { Component } from '@angular/core';
-
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css']
- })
- export class AppComponent {
- title = 'Data binding using String Interpolation';
- }
In the app.component.ts file, we have a variable called “title” which has a string value. We want to display this title value on the app component HTML view to the user.
app.component.html
In the app.component.html file, we have used title variable for displaying title value. Now when this view will be rendered in the browser, title value will be displayed over the page.
Output
String Interpolation can resolve some other expressions. We have a few examples of it below –
Example 1
Let’s initialize two variables with two numbers and display their addition on the view.
- export class AppComponent {
- title = "Data binding using String Interpolation";
- numberA: number = 10;
- numberB: number = 20;
- }
In the View, the expression will look like below –
<p>Calculation is : {{ numberA + numberB }} </p>
Output
Example 2
Let's define a method in the TypeScript code and call it in the View.
- export class AppComponent {
- title = "Data binding using String Interpolation";
- numberA: number = 10;
- numberB: number = 20;
-
- addTwoNumbers() {
- return this.numberA + this.numberB;
- }
- }
Now, call this method in View and see the output.
<p>Addition is : {{ addTwoNumbers() }} </p>
Output
Property Binding
Property binding is also a one-way data binding, where we bind a property of a DOM element to a field which is a property we define in our component typescript code. Behind the scene, Angular converts string interpolation into property binding.
For Example – <img [src]=”imgUrl” />
However, we can use string interpolation here like <img src=”{{ imgUrl }}” /> , but property binding is always a lot cleaner and shorter syntax to bind image source.
My recommendation is when you want to simply display some dynamic data from a component on the view between headings like h1, h2, p etc, use string interpolation.
Suppose if you will use property binding for just displaying some value between h2 heading; the syntax will be –
<h2 [textContent]="title"></h2>
Here, we are binding the text content property of h2 DOM element with the title property that we defined in our component. You can see that this syntax obviously is longer than string interpolation one.
Note
String Interpolation and Property binding both are one-way binding. That means if field value in the component change, Angular will automatically update the DOM. But any changes in the DOM will not be reflected back in the component.
app.componnt.ts
Let’s define a property named “imgUrl” and bind this with an image tag in the template.
- export class AppComponent {
- title = "Data binding using Property Binding";
- imgUrl="https://avatars2.githubusercontent.com/u/20270535?s=40&v=4";
- }
app.component.html
Use this property in the View and see the output.
- <h2>{{ title }}</h2> <!-- String Interpolation -->
- <img [src]="imgUrl" /> <!-- Property Binding -->
Output
Event Binding
Angular provides us with other types of binding, i.e., event binding, which is used to handle the events raised from the DOM like button click, mouse move etc. Let’s understand this with the help of an example –
Suppose we have a button in the HTML template and we want to handle the click event of this button. To implement event binding, we will bind click event of a button with a method of the component.
app.component.html
app.component.ts
- export class AppComponent {
- onSave(){
- console.log("Save operation is performed!");
- }
- }
Output
When a user clicks on this button, the button click event will fire and onSave method will be called, which will log a message in the console.
Access DOM event object using $event
Sometimes we need to access the event object that is raised in the event handler. For example on mouse move, we need to access the x and y positions using DOM event object, then we have to pass $event as a parameter. Let’s understand this with the help of an example –
app.component.html
app.component.ts
- export class AppComponent {
- onSave($event){
- console.log("Save button is clicked!", $event);
- }
- }
Output
Event Bubbling
All the DOM events bubble up to the DOM tree unless a handler prevents further bubbling. This is just standard event propagation mechanism in DOM. Let’s understand this with the help of an example.
Let’s proceed with the button example. I have a div wrapper around the button in component HTML and div has also a click event handler just to log some message if div is clicked.
app.component.html
- <h2>Event Bubbling Demo</h2>
-
- <!-- Event Bubbling -->
- <div (click)="onDivClick()">
- <button (click)="onSave($event)">Save</button> <!-- Event Binding -->
- </div>
App.component.ts
- export class AppComponent {
- onSave($event){
- console.log("Save button is clicked!", $event);
- }
- onDivClick(){
- console.log("DIV is clicked!");
- }
- }
Output
Now let’s see the output. When we click the button, there are two messages logged in the console. One is from the handler of the click event of the button and second is from the handler of the click event of the div.
This is what we call “Event Bubbling”, an event bubbles up the event of its parent element.
If we would have another div or another element as a wrapper around of the div element and we handle the click event of that element, our button event will bubble up against the events of entire DOM tree.
To stop this event bubbling, we use stopPropogation method.
- export class AppComponent {
- onSave($event){
- $event.stopPropagation(); <!--Stop event bubbling -->
- console.log("Save button is clicked!", $event);
- }
- onDivClick(){
- console.log("DIV is clicked!");
- }
- }
And now, when we click on the Save button, only the onSave method will be executed and will see only a message coming from the handle of the click event of the button.
Event Filtering
Angular provides a feature called Event Filtering. Let’s understand this with the help of an example.
Suppose I have a textbox and I want to log the text (which is entered in the textbox) in the console on pressing enter. Below is a traditional way to implement it.
app.component.html
- <h2>Event Filtering Demo</h2>
- <input (keyup)="onPressEnter($event)" />
app.component.ts
- export class AppComponent {
- onPressEnter($event){
- if($event.keyCode===13){
- console.log("Entered text: ",$event.target.value);
- }
- }
- }
Output
Angular provides a shorter and cleaner way to implement the same. Let’s implement it with Angular event filtering.
app.component.html
- <h2>Event Filtering Demo</h2>
- <input (keyup.enter)="onPressEnter($event)" />
Just had to add enter filter with keyup event.
app.component.ts
- export class AppComponent {
- onPressEnter($event){
- console.log("Entered text: ",$event.target.value);
- }
- }
And now, you can see there is no need to write that key code (13) and compare with.
Output
Two-Way Data Binding
Angular provides a very nice feature; i.e., two-way data binding. As of now, we have seen how to bind component data to view using one-way bindings. That means any change in the template(view) will not be reflected in the component typescript code.
Now, two-way binding has a feature to update data from component to view and vice-versa.
Syntax - For two-way data binding, we combine property binding and event binding both. Also, we can call “Banana in the Box”.
[(ngModel)] = ”[property of your component]”
Important Note
To implement two-way data binding, you need to enable the ngModel directive and this depends upon FormsModule in angular/forms package. So you need to add FormsModule in imports[] array in the AppModule.
app.module.ts
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
- import {FormsModule} from '@angular/forms';
- import { AppComponent } from './app.component';
-
- @NgModule({
- declarations: [
- AppComponent
- ],
- imports: [
- BrowserModule,
- FormsModule
- ],
- providers: [],
- bootstrap: [AppComponent]
- })
- export class AppModule { }
app.component.html
- <h2>Two-way Binding Demo</h2>
- <input [(ngModel)]="fullName" /> <br/><br/>
- <p> {{fullName}} </p>
app.component.ts
- import { Component } from "@angular/core";
-
- @Component({
- selector: "app-root",
- templateUrl: "./app.component.html",
- styleUrls: ["./app.component.css"]
- })
- export class AppComponent {
- fullName: string = "Rahul";
- }
Now, ngModel will trigger the input event and update the value of input textbox in our view and when we will change the value of the textbox, it will automatically update in the “fullName” property of our component and vice-versa (as shown with the help of including string interpolation inside a paragraph).
Output
Summary
Data binding in Angular is used to bind data from component to view and from view to a component. There are two directions of data binding, first is one-way data binding (using string interpolation, property binding) and the second is two-way data binding (using ngModel). We learned through this article String Interpolation, Property Binding, Event Binding, Event Bubbling, Event Filtering and finally two-way data binding.
You can download the complete project with data binding examples from here.
Write to me in the comment box in case you need any help or you have any questions or concerns. Have a good day!