Pull to refresh

A Quick Guide To Angular Pipes

Reading time4 min
Views2.1K

Impressive web development is the result of a successful synergy of robust back-end and an appealing front-end. Usually, the back-end is thought to be the ‘brains’ of a webpage and the front-end is merely the shiny exterior. However, with the right front-end development framework, powerful computations can happen directly on the front-end as well. Angular happens to be one of such impressive front-end development frameworks. Through its templates, Angular offers the opportunity for data to be processed and formatted in a certain way right there in the HTML code. This is made possible through functions with easy-to-understand syntax and usage, and they are called pipes.

This article will serve as a quick guide to tell you all the meaty stuff to know about pipes and how to effectively use them. Pipes come in various types and can significantly simplify data collection and processing in use cases where the front-end is the main gateway of obtaining the data. The article will also discuss how pipes are tested during the unit testing of Angular applications (which is not as difficult as it may seem for some).

The Ins And Outs Of Angular Pipes

Before moving on to discussing Angular pipes, it is imperative to understand what Angular components and templates are. Pipes are present in the template part of the component, making it necessary to understand the former to grasp the utility of the latter.

Angular applications are fundamentally made up of units called components. Each component is centered around a certain functionality or visual aspect of the application. These components are self-contained and consist of both its working logic along with instructions about its visual rendering. The latter is stored in what are called templates. Templates are simply HTML code that can be in the form of a separate file or inline code within the @Component decorator (which is written in TypeScript). An example of an Angular component can be seen below.

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

@Component({
	selector: 'ang_app_example',
	templateUrl: './component.ang_example.html',
	styleUrls: ['./component.ang_example.css']
})

export class ExampleAngApp implements OnInit {
	constructor() { }
}

Here, the template URL is storing the relative path to a separate HTML file stored in the respective directory.

Usually, the functionality of the template is to mainly describe the visual layout of the component and show any data that is required. However, in cases like template-driven forms, the data that the back-end has to work with is mainly received through the front-end. Examples of these include a form taking in the personal details of a customer or information about a shipping order. The data received in such cases is mainly in the form of strings and instead of passing them as is to the back-end, pipes help us format them beforehand.

Pipes result in significant simplification of back-end logic and a smoother application, as in the above scenario. Oftentimes, data needs to be formatted in a particular way before being displayed. Once again, pipes come to the rescue here and avoid unnecessarily long code. One thing to note here is that pipes do not change the value of the variable, rather just formats it and inputs it as directed.

Using All The Different Kinds Of Angular Pipes

Pipes are used in the HTML code through the pipe operator ( | ). On one end of the operator, the variable whose value is to be formatted is placed and the particular formatting function(s) on the other hand. There can be multiple such functions, as we shall see in a bit. Given below is a short example of a simple pipe in action.

<p>Today's date is {{todayDate | date}}</p>

Here the date function is being used to simply format the value of todayDate into a regular date format. A specific format can be further specified, as in the example below. Through the fullDate, we also get the day today along with the full date.

<p>Today's date is {{today | date:'fullDate'}}</p>

One of the most interesting aspects of pipes is that they can be chained so that the data can undergo multiple formattings. In the following example, we obtain the date all in uppercase. Something similar is possible for formatting it into lowercase or even titlecase.

<p>The hero's birthday is {{ birthday | date | uppercase}} </p>

Various kinds of pipes exist, such as date, currency, decimal, JSON, and percentage, to name a few. However, the need to construct custom formatting can always arise in the rapidly expanding world of web development. That can be catered to through coding a particular pipe as required. Creating one’s own pipes is highly encouraged as it promotes easier-to-understand code and reusability of functionality throughout the code. Given below is an example of coding a custom pipe that raises a value to the exponent of some power given as well.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'raiseExponential'})
export class raiseExponentialPipe implements PipeTransform {
	transform(value: number, exponent = 1): number {
		return Math.pow(value, exponent);
	}
}

This pipe can now be used for a value in the following manner.

<p>Two to the exponent 10 is: {{2 | raiseExponential: 10}}</p>

Pipes are mainly of two types:

  1. Pipes that first check if the data is bound to a certain variable has changed with any kind of event and then run to update the value. These are called pure pipes.

  2. Pipes run every time there is an event. These are called impure pipes.

As anyone can tell, it is better to strive towards creating pure pipes as the other kind can have a significant effect on the performance of the application. Impure pipes can prove expensive especially when used in chaining.

Testing Angular Pipes

Once an Angular application is complete, its unit testing is essential to further polish it and improve in any way necessary. If the said Angular application implements pipes for its purposes, then they are to be tested too. In particular, the pipes are tested to see if the formatting is working as intended and is handling corner cases as well. As pipes are straightforward functions that take in an input and throw out an output, testing pipes is really easy. Simply, they are provided with all kinds of boundary values to test if the transform() function is handling all kinds of parameters well and is giving intended values.

Conclusion

We saw how pipes can be used in our Angular applications to further improve its performance and do something as mundane as data formatting right there in the front-end. The article showed you all the different ways you could use pipes, alone and in chains, and the different kinds of pipes there are. To find out the full list of pipes provided by Angular itself, one can check out their pipes API documentation. We saw that testing the pipes is fairly easy and mainly focuses on the transform() function that the pipe implementation uses at the back-end. We discussed pure and impure pipes and also learned why the former is encouraged while the latter is discouraged.

Tags:
Hubs:
Rating0
Comments0

Articles