Angular — Transform Data with Pipes

Jawadhasan
3 min readJun 17, 2023
Photo by Samuel Sianipar on Unsplash

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:

--

--

Jawadhasan

Software Solutions Team Lead | Cloud Architect | Solutions Architect