Angular – Transform Data with Pipes

Introduction

We use pipe for transforming bound properties before displaying them in a view.

Angular provides us with few built-in pipes e.g. date, number, decimal, percent, currency, json etc.

This time, we want to build our own custom pipe.

Use Case

Build a custom pipe which replaces ‘-‘ character with a space ‘ ‘.

It could be a product-code e.g. “prod-1, prod-2” or similar data where we want to perform transformation before displaying it.

Solution

We could build a custom pipe to replace dashes with spaces.

But let’s build a more generalized custom pipe, that transforms any specified character in a string to a space.

Pipe Structure

Following is the Skelton for our custom pipe . It has a Pipe decorator with a name property. Inside the pipe there is a transform function.

We write code in this transform method to transform a value and return it.

The first parameter is the value and other parameters are arguments to the function.

Following picture shows the implementation of this pipe. It is using a simple JavaScript function for transformation:

To use this pipe, we need to add it to the declarations array of the module (e.g. app.module.ts)

Now, we can use this pipe inside this module.

Usage

We’ve following data displayed in our application and we’ll now use our custom pipe to replace the dash from the device name with space. It is a very simple example, but will help us to see the pipe in action:

To transform dash with space, we’ll use the pipe in our html template as follows

and following is the result after applying the pipe

Example 2

We have a notes page in our angular application which displays note data along with its category:

Category is currently shown as a number, however, we would like to transform this number into a text description.

Lets create a custom pipe for this application specific requirement.

again, very simple logic here and after adding this pipe into declarations array of the module, we can use it as follows:

and results as below

You can download the source code from this git repository.

The deployed sample application is available on this URL.

Summary

Build a custom pipe anytime you need to perform application unique data transformations.

In this post, we learned about how to create a custom pipe and use it for data transformation.

Let me know if you have some questions or comments. Till next time, Happy Coding.