In this section, we’ll walk through building a custom Pipe. If you’re new to Pipes and how they function in Angular, I suggest checking out my earlier posts on the topic—feel free to begin with this one


When the built-in Pipes fall short of what you need, that’s exactly when a custom Pipe becomes useful.

✩ Let’s jump into crafting your very first one. ✩

To generate a Pipe via the CLI, run this command—
ng generate pipe <pipe-name>

or, for short
ng g p <pipe-name>

Lets open the command prompt in the project root and type in the below command -
ng g p custom-pipe-demo
So here we are saying Angular to create a pipe with the name
custom-pipe-demo
Creating Custom Pipe in Angular — figure 1
and you will see 2 files getting created in the project -
Creating Custom Pipe in Angular — figure 2
The file pointed with the red arrow is the spec file (for writing unit test). We will not talk about it right now.
We are more interested in writing our first pipe and will work with the file pointed with yellow arrow (the second one).

One more line we can see in the command prompt which tells that the app.module.ts has been updated.
If you open the app.module.ts file you will see a new line got added and its the name of our pipe.
Creating Custom Pipe in Angular — figure 3
I will talk about modules in very details in the very next post.

So lets see how the pipe looks like -

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

@Pipe({
  name: 'customPipeDemo'
})
export class CustomPipeDemoPipe implements PipeTransform {
  transform(value: unknown, ...args: unknown[]): unknown {
    return null;
  }
}
Enter fullscreen mode Exit fullscreen mode

Here are the key points we should take note of —
1️⃣ A standard TypeScript class, CustomPipeDemoPipe, is present.
2️⃣ The class implements the PipeTransform interface.
3️⃣ The class is decorated with @Pipe.
4️⃣ The @Pipe decorator accepts an object containing the pipe’s name.
5️⃣ Within the PipeTransform interface, there is a transform method that must be implemented (🔴 this is mandatory 🔴).
6️⃣ The transform method takes several parameters. Its signature is pre-defined, yet we are free to adjust it to fit our requirements. The first parameter represents the value to be transformed, while the subsequent parameters form an array of all pipe arguments. Recall how we supplied 'short' or 'medium' as arguments to the date pipe.
7️⃣ The type defaults to unknown, but we have the flexibility to alter it.

With that in mind, the next consideration is what exactly we aim to create using this pipe.

Let’s imagine our project includes a file picker. After a file is selected from the system, we want to display its size in megabytes by default; however, if a unit like GB is passed, the pipe should convert the size accordingly.

To move forward, we’ll copy the code below and customize the transform function —

  transform(fileSize: number, ...args: string[]): string {
    if (!args.length || args[0] === 'MB') {
      return (fileSize / (1024 * 1024)).toFixed(2) + 'MB';
    } else if (args[0] === 'KB') {
      return (fileSize / 1024).toFixed(2) + 'KB';
    } else {
      return (fileSize / (1024 * 1024 * 1024)).toFixed(2) + 'GB';
    }
  }
Enter fullscreen mode Exit fullscreen mode

and in the app.component.html file -
Creating Custom Pipe in Angular — figure 4

Lets paste in the below code -

<h3>Custom Pipe Demo</h3>
<p>{{ 2000405677 | customPipeDemo : 'KB' }}</p>
Enter fullscreen mode Exit fullscreen mode

Let’s examine the code at a high level.
The initial parameter received by the transform function is the value to be changed — here, that’s 2000405677.
Next, we apply the pipe operator (|), followed by the pipe name customPipeDemo.
We may then supply an argument, such as the target unit for conversion — in this example, KB.
Multiple arguments can also be provided, and they’ll arrive inside the args array within the transform function.

In the output we will see -
Creating Custom Pipe in Angular — figure 5

Lets see what debugger tells us -
Creating Custom Pipe in Angular — figure 6

In this example, the fileSize argument is assigned the value
2000405677
and args[] stores KB as the first element from the array supplied in the call.

Important:
The returning keyword carries the utmost significance.
Once the transformation is complete, the updated value must be returned; otherwise, the template or browser displays nothing.

That wraps it up for now, friend 👋🏼

I trust you found the article enjoyable.
If so, don’t forget to like, comment, and share.
The next topic lined up is the Module in Angular. Keep an eye out.

Salute!!!
Code with joy