Learn Events Handling and Data Binding with Pipes in Angular

Introduction

In this article, we will learn data binding features and transform bound data with pipes. It provide a great interactive user experience, and we want to bind DOM elements to component properties. so, the component properties can change the look and feel as needed. here, We are going to use bindings to change element colors or styles based on data values. update font size based on user preferences, or set an image source from a database field. we want to notification of user actions and other events from the DOM. so the component can respond.

For example, we can respond to a click on a button to hide or show images. so, we want the best of both worlds using two-way binding to set an element property and receive event notifications of user changes to that property. further, we’ll use Angular’s property binding to set HTML element properties in the DOM, we’ll understand how to handle user events such as a button click with event binding, and also how to handle user input with two-way binding.

After that, we’ll discover how to transform bound data with pipes. And here once again is our application architecture. We have the first cut of our Car list component, but it doesn’t have any interactivity. In this module, we’ll use data binding features to add interactivity to the Car list component. Let’s get started

Property Binding

Property binding allows us to set a property of an element to the value of a template expression. In the following example, we bind the source property of the image element to the imageUrl property of the Car. defining the source of the image from information in our component class. Our binding target is always enclosed in square brackets to the left of the equals and identifies a property of the element.

<img [src]='Car.ImageUrl' >

The binding source is always enclosed in quotes to the right of the equals and specifies the template expression. here, is a similar binding using interpolation.

 <img src={{Car.ImageUrl}}>
 
 <img src='http://example.com/{{Car.ImageUrl}}'>

The element property is not enclosed in square brackets and the template expression is enclosed in curly braces with no quotes. If you need to include the template expression as part of a larger expression. such as this example, you may need to use interpolation. Like interpolation, property binding is one way from the source class property to the target element property. It allows us to control our template’s DOM from our component class.

Add Property Binding

Now, let’s add some property binding to our sample application.

<div class='table-responsive'>
	<table class='table' *ngIf='car.Price > 50000' >
    <tr *ngFor='let car of cars'>
		<td>{{car.Name}}</td>
		<td>{{car.Color}}</td>
		<td>{{car.Price}}</td>
		<td><img [src]= 'Car.ImageUrl' [style.width.px]='Width' [style.Height]='Height'></td>
	</tr>	
    </table>
</div>

Let’s use property binding to bind the source of our car image. We use an image element to display our car image, and we use property binding to bind the image’s source or src property. So we enclose the src in square brackets. On the right side of the equals, we define the template expression in quotes. We want to bind to the Car’s imageUrl property from the CarListComponent class.

Now, let’s go to the component, and here, we defined an array for our list of Cars. Here, At the Car list component and its associated template.

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

@Component({
	selector: 'root-car',
	templateUrl: './car-list.component.html'
})
export class CarListComponent {
	width: number=250;
	Height: number=250;
	cars: any[] = [
	{
	  "Name":"Ferrari",
	  "Color":"yello",
	  "Price":$60000,
	  "ImageUrl":'http://example.com/ferrari.jpg'
	},
	{
	  "Name":"Tesla",
	  "Color":"red",
	  "Price":$70000,
	  "ImageUrl":'http://example.com/tesla.jpg'
	},
	{
	  "Name":"Benz",
	  "Color":"white",
	  "Price": $80000,
	  "ImageUrl":'http://example.com/benz.jpg'
	}
	]
}

Handling Events with Event Binding

So, all our data binding has been one way from the component class property to the element property. But there are times we need to send information the other way to respond to user events.

<button class='btn btn-primary' (click)='toggleImage()'>Clcik Here</button>

For example, to perform an operation when the user clicks a button, a component listens for user actions using event binding as shown here. Notice how similar the syntax is to property binding.

In this example,

//car-component.html

<div class='table-responsive'>
	<table class='table' *ngIf='car.Price > 50000' >
    <tr *ngFor='let car of cars'>
		<td></td>
     	<td>{{car.Name}}</td>
		<td>{{car.Color}}</td>
		<td>{{car.Price}}</td>
		<td><img [src]= 'Car.ImageUrl' [style.width.px]='Width' [style.Height]='Height'></td>
	</tr>	
    </table>
</div>

The component listens for the click event on a button. The name of the bound event is enclose in parentheses, identifying it as the target event. To the right of the equals is the template statement. This is often the name of a component class method followed by open and closing parentheses and enclosed in quotes. If the defined event occurs, the template statement is executed, calling the specified method in the component.

Next, we build the method that the event binding will call. By convention, methods are created after all the properties are defined, so we’ll put it down here. Let’s name the method toggle image.

//cars-component.ts

toggleImage(): void {
		this.showImage = !this.showImage;
}

Notice that TypeScript does not need any keywords such as function. the method won’t have a return type, so we specify the return type as void. The body of the method toggles the state of the showImage property.

In the template, we are ready to set up the event binding. On the button element, we define the click as the target event by enclosing it in parentheses. We assign it to our method enclosed in quotes. When the user clicks the button, the binding calls our method. so the only thing left is to actually hide or show the image. We only want this image element if the showImage flag is true, so we type *ngIf=’showImage’. The image element will then only add to the DOM if showImage is true.

//car-component.html

<div class='table-responsive'>
	<table class='table' *ngIf='car.Price > 50000' >
    <tr *ngFor='let car of cars'>
		<td></td>
     	<td>{{car.Name}}</td>
		<td>{{car.Color}}</td>
		<td>{{car.Price}}</td>
		<td><img *ngIf='showImage' [src]= 'Car.ImageUrl' [style.width.px]='Width' [style.Height]='Height'></td>
	</tr>	
    </table>
</div>

Transforming Data with Pipes

With Angular’s data binding, displaying data is easy. The Pipes transform bound properties before they display. so we can alter the property values to make them more user-friendly or more locale-appropriate. Angular provides some built-in pipes for formatting values, such as date, number, decimal, percent, currency, uppercase, lowercase, and so on.

Angular also provides a few pipes for working with objects. such as the JSON pipe to display the content of an object as a JSON string. which is helpful when debugging, and a slice pipe, which selects a specific subset of elements from a list. We can also build our own custom pipes.

Lowercase & Uppercase

Let’s start with a simple example. we want to display the Car Name in lowercase. We can add the pipe character after the property in the template expression, and then specify the lowercase pipe. The Car code is then transformed into lowercase before it display. We can also use pipes in property bindings.

 {{car.Name | lowercase }}

Add the pipe after the property in the template expression and specify the desired pipe. In this example, we specified the uppercase pipe.

 <img [src]='car.Name | lowercase'>

Currency

In this example, the price transform into a currency. By default, the currency pipe adds all caps, three-letter abbreviation of the local currency to the amount. If we want to display that abbreviation in lowercase, we can transform it again by adding another pipe.

{{car.Price |currency | lowercase}}

Some pipes support parameters. Parameters define by specifying a colon and the parameter value. For example, the currency pipe has three parameters. the desired currency code, a string defining how to show the currency symbol, and digit info. The digit info consists of the small number of integer digits. the small number of fractional digits, and the largest number of fractional digits.

 {{car.Price | currency:'USD' : 'symbol':'1.2-2'}}

The value here of 1.2-2 means that at least 1 digit to the left of the decimal. and at least 2 digits to the right of the decimal. and no more than 2 digits to the right of the decimal, defining 2 decimal places.

So, in this article, we understand the Data binding makes it easy to display class properties from our component. and set DOM element properties to our class property values to better control the view. the component can listen for events from the DOM to respond as needed for interactive user experience.

Leave a Reply

Your email address will not be published. Required fields are marked *