Custom Pipes in Angular

In last chapter we have learnt about the built in pipes in angular. Now in this chapter we will see custom pipes and how we can create the custom pipes.

As we already know Pipes are a useful feature in Angular. They are a simple way to transform values in an Angular template. A pipe takes any value as an input and returns some output.

Lets see how we can create the custom pipe. To create the custom pipe use below command –

pipes

So this command will create two files one is .ts file and another one is .spec.ts file. If you will see the ts file so it will look like this –

In above code you can see pipe is nothing but a class which is decorated by pipe metadata @Pipe. Here custom is the name of our pipe. The pipe class must implement the PipeTransform interface’s transform method that accepts an input value followed by optional parameters. So whatever the logic you want to implement in pipe you need to write inside the  transform method.

For using this pipe you need to add the below code in html file or template from where you want to use this pipe.

 

Lets understand more it by one simple example-

Suppose we want to get the square of any number then use below code in your ….pipe.ts file

In this code inside the transform method we are just multiplying the number and returning its value. Now add below code your template –

So you will get the output as 25.

Also we can pass parameters to pipe. Let see how we can do it.

Passing parameter to custom pipe : In above example we have passed only the number for which we want square. but now we will pass exponent value as well, which decides how many times we have to multiply the number. So add the below code in ts file.

So you can see inside the transform method we are getting the two parameters one is the actual number and 2nd one is the value of exponent. And we are using Math.pow() function to do the multiplication.

In html file or template add the below code.

So it will return the 125 as an output.

Similarly we can pass the multiple parameters to pipe also which should be colon(:) separated. And in transform method also you need to get that parameters also. for example –

 

Conclusion: In this tutorial we learnt how to create a custom pipe and reference it inside our html and .ts code. Although, this was a very simple example however the fundamentals for creating a pipe does not change when creating a more complex one.

Now that you know how to create a custom pipe. I hope this tutorial will be helpful and beneficial for you.

 

 

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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