Angular — Understanding pipes and Different ways to use them
By: Bhargav Bachina
Tags: JavaScript, Angular Pipe, Typescript, Angular Tutorial, Angular For Beginners

Angular — Understanding pipes and Different ways to use them

Exploring Angular pipes with examples

Sometimes we want to change data from API or some other source by editing it before we put that in the template. It’s okay to edit in the component if the data is private to one component. what if we have to do this in a lot of components in the app?

It’s not best practice to do that multiple places in the app. Angular pipes are a great way to use for these scenarios. Pipes take the input and transform it in a desired way and outputs in the template.

Let’s understand pipes and different ways to use them.

Angular pipes

Here is the list of things we will go through in this article

How to use pipes in Templates

How to use pipes in Component Class

How to pass parameters to pipes in templates

How to pass parameters to pipes in the Component class

chaining pipes

example project

All Built-in Pipes

How to create Custom pipes

How to use Custom pipes

Pure pipes

Impure pipes

How to create custom impure pipes

Understand the difference with an example

We can use pipes in both templates and component class. Let’s see how we do that

How to use pipes in Templates

It’s simple to use pipes in templates all we need to use this symbol |. If we look interpolation expression at line 3, we are using pipe uppercase with the title which transforms the title to uppercase.

Usage of pipes in templates

pipes in action

How to use pipes in Component Class

Usage of pipes in component class is a little bit different. First, we need to import pipe from Angular common library (line 2) and add it to providers array (line 8) of the component and then we need to inject in the constructor of the class(line 12).

Now the pipe is ready to use in the component and every pipe has transform method which takes inputs and the result will be applied to the title here (line 14).

Usage of pipes in the component class

How to pass parameters to pipes in Templates

We can pass parameters to the pipe. we have to use a specific format to pass parameters. Let’s look at the below example pipe DecimalPipe where we are using the colon: followed by the pipe (line 12,16, 20) to pass locale and specific way to display numbers. we can pass multiple parameters as well.

Usage of Decimal Pipe

How to pass parameters to pipes in Component Class

Let’s see how we can pass parameters to pipe in component class. If we can look at the below file that we are passing as arguments to the transform method at line 14.

Usage of pipes in the Component class

chaining pipes

We can chain pipes in templates. Let’s take an example for slicepipe and uppercase to display string in uppercase after slicing operation.

chaining pipes

Here is the output

chaining in action

Example Project

Here is an example project I created to test all the pipes. You can clone it from here.



git clone // clone itgit clone https://github.com/bbachi/angular_pipes.git // install all dependencies

npm install // start the project

npm start

example project in action

built-in pipes

Angular provides some built-in pipes which we can use in our projects right out of the box. Let’s understand some of these and how to use them.

LowerCasePipe

UpperCasePipe

TitleCasePipe

DecimalPipe

CurrencyPipe

JsonPipe

PercentPipe

DatePipe

KeyValuePipe

SlicePipe

AsyncPipe

LowerCasePipe

This pipe is used to transform your data into lowercase. It doesn’t matter how you enter data it always appears in lowercase on the screen.

lowercase pipe usage in template

lowercase pipe in action

UpperCasePipe

This pipe is used to transform your data into uppercase. It doesn’t matter how you enter data it always appears in uppercase on the screen.

uppercase pipe usage in template

uppercase pipe in action

TitleCasePipe

This pipe is used to transform your data into title case. It means every letter of the beginning of the word is capitalized.

titlecase pipe usage in template

titlecase pipe in action

DecimalPipe

This pipe is used to format the decimal/number. Here are the number of scenarios where we can pass parameters to this pipe. With no parameters, the minimum and maximin digits are 0 and 3 respectively and it also takes a locale as the second parameter.

//format of this pipe {{expression | number:'<intergerdigits>.<minfractional digits-max fractional digits>':'locale'}}

decimal pipe in action

CurrencyPipe

This pipe is used to format the currency. Here are the number of scenarios where we can pass parameters to this pipe. With no parameters, the default symbol is $ respectively and it also takes a locale and digits info as the other parameters.

currency pipe

currency pipe in action

JsonPipe

Sometimes we want to show the json representation of the object. This pipe is exactly for that. Look at the following files and output of this json pipe. So, we can output the person object in a json format with json pipe.

files to showcase json pipe usage

Json pipe in action

PercentPipe

This pipe is used to transform a number into percentage strings. Here are the number of scenarios where we can pass parameters to this pipe. With no parameters, the minimum and maximin digits are 0 and 3 respectively and it also takes a locale as the second parameter.

percent pipe

percent pipe in action

DatePipe

It’s very common to format the date and display it on the screen for the user. This pipe is used to format the date in different ways. Let’s see some examples.

different ways of using datepipe

datepipe in action

KeyValuePipe

This pipe is used to output the map, objects into key-value pairs. Let’s look at the following files to see the different ways of using it. We can use compare function (line 18) if keys are complex or we want to display in a specific order.

Usage of keyvalue pipe

Here is the keyvalue pipe in action. Look at the Compare function output, we are displaying names in the alphabetical order with the help of orderByNames compare function.

keyvalue pipe in action

SlicePipe

This is pipe is used to return the copy the selected items from the array or substring from the string for the range specified. Here is an example.

Usage of Slice pipe

slice pipe in action

AsyncPipe

This pipe is used to subscribe to observables or promises and get the latest data from them. When it is used with Observables, it invokes the change detection for the component every time it receives the new value and unsubscribes to the observable to avoid memory leaks when the component gets destroyed.

Let’s look at the below example. Whenever we fill the form and click on addToPromise or addToObervable methods, we are updating promise or observables and our templates updates because of the async pipe.

async pipe example

async pipe in action

How to create Custom pipes

Basic Pipe

Creating custom pipes are easy. All we have to do is extends PipeTransform interface and implements the default method transform.

Let’s look at the below custom pipe, It takes the name and transforms it by appending “My Name is:”

custom pipe myName

Pipe with parameters

Let’s modify the same to take arguments. what if we want to give preference to the user to show it in uppercase, lowercase or titlecase.

Let’s look at the below file. We don’t have to do anything special here, we just need to use optional args in the transform method

custom pipe myNamewithpref which takes params

How to use Custom pipes

There is nothing special using custom pipes as well. All we need to do is import custom pipes in particular module and use it as if there are built in pipes.

If we look at the below files. we import pipe and declare it in the declarations array and use it in our component templates as there are builtin pipes.

Custom pipes in action

custom pipes in action

Pure Pipes

Angular uses Pure pipes by default and it only executes these pipes if there is any pure change in the input value(any primitive value change or any object reference change). It also uses pure functions which don’t have any side effects. This is because we don't want to execute pipes for every change detection.

lowercase, uppercase, titlecase and out custom pipes myname are pure pipes

Impure Pipes

Angular executes impure pipes for every change detections which means it is executed very often probably for every few milliseconds. we have to use these with a lot of care for performance reasons. These pipes are stateful.

AsyncPipe, SlicePipe are impure pipes

How to create Custom Impure pipes

Every pipe decorator has a name and pure as metadata. If we want to make the pipe impure, we have to define pure as false as shown in the below file. Other than this it is pretty similar to a normal pipe.

Impure pipe

Understand the difference with an example

Angular executes pure pipes only with primitive changes or object references and not with every change detection

Angular executes Impure pipes with every change detection.

For example, we have items array defined in the component and we are adding items from the template every time we click add and we have pure printout pipe and printoutimpure pipe where it prints out item array in a string format.

usage of pure and impure pipes

Now, every time we add an item only items with printoutimpure will be updated with the added items. This is because printoutimpure is an impure pipe which is executed with each change detection.

impure pipes in action

Conclusion

We often manipulate data in our apps. we can use pipes not to repeat ourselves in a lot of places. Since all the logic in one place, we could even unit test this logic.