DEV Community

Anubhab Mukherjee for This is Angular

Posted on

Creating Custom Pipe in Angular

Today we will learn how to create our own Pipe or the Custom Pipe. If you are unaware about what a Pipe is in Angular then I would recommend you to go through the previous articles I wrote on Pipe. You can start from here


The need of custom pipe comes when the built in pipe does not meet our requirement.

✩ So now lets see how can we create our first Pipe ✩

The CLI command to create a Pipe is -
ng generate pipe <pipe-name>

the shorthand -
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
Image description
and you will see 2 files getting created in the project -
Image description
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.
Image description
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

Lets note our observation points -
1️⃣ There is a normal typescript class CustomPipeDemoPipe
2️⃣ The class implements an interface PipeTransform
3️⃣ The Class is marked with a @Pipe decorator
4️⃣ The Pipe Decorator takes an object, which has the name of the pipe
5️⃣ The PipeTransform interface has a method called transform which we need to implement (🔴 its mandatory 🔴)
6️⃣ The transform method has few arguments. The signature is already provided but we need to tweak it as per our need. The first argument is the value which we need to transform and the remaining args is an array of all the pipe parameters. Remember when we used the date pipe we passed 'short'/ 'medium' etc as parameters.
7️⃣ The type is unknown by default but we can change it.

So now the next question what we are trying to build using the pipe.

Say our project has a file picker. Once it picks a file from the system we need to show the file size in Mb by default and if we pass a unit like GB it will convert that accordingly.

So lets paste the below code and modify 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 -
Image description

Lets paste in the below code -

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

Lets understand the code on a high level.
The first parameter which will come to the transform function is the value that we need to transform/ alter. In this case 2000405677
Then we are using the pipe operator (|) and then the name of the pipe customPipeDemo
Then we can pass an argument in this case the unit where we need to convert to in this case KB
You can pass multiple arguments also and will be received by the args array, in the transform function.

In the output we will see -
Image description

Lets see what debugger tells us -
Image description

Here you can see the argument fileSize receives the value
2000405677
The args[] receives KB as the first item in the array which we were passing in the argument.

Note:
The most important thing is the return keyword.
After we did the transformation you can see we need to return the transformed value else nothing will be displayed in the template/ browser.

That's all for now my friend 👋🏼

Hope you enjoyed the reading the post.
If yes do like comment and share.
Coming up next is the Module in Angular. So stay tuned.

Cheers!!!
Happy Coding

Top comments (0)