Creating Custom Pipes in Angular

Previously known as Filters in AngularJS, Custom Pipes can be of two types. Pure and impure custom pipe. Pipe takes an input and returns an output based on the output of transform function evaluation.

Usage of Pipes

Angular has many built-in pipes. In this article, we’ll see how to create a custom one.

Steps Involved In Creating a Custom Pipe In Angular are:
1) Create a Pipe Class and decorate it with the decorator @Pipe.
2) Supply a name property to be used as template code name.
3) Register your Pipe in the module under declarations.
4) Finally, implement PipeTransform and write transformation logic.
5) Use your pipe in the HTML using ‘|’, which represents a pipe.
6) Also, add Custom arguments if you want to.

Once we are done creating the Pipe class, we go to app.module.ts and register our pipe.Once we are done creating the Pipe class, we go to app.module.ts and register our pipe.

To finally put some logic behind the task of our custom pipe, we use PipeTransform.

So, to maintain the required contract to adhere to the standard structure, we use transform() method inside PipeTransform.

Now, our motive is to convert some random number to a readable format of megabytes, and to do that, we put logic inside transform() as follows:

Now to use it in the HTML,

To add a custom argument to your output, simply add the capability of extension to the Transform() method as follows.

We can also add multiple arguments which can be separated using ‘:’
For example,

{{ result| pipe:argument1:argument2 }}

Leave a comment

Your email address will not be published. Required fields are marked *