In this article we will learn about how Angular Pipes works and how we can create our own Angular Custom Pipes for our needs.
Youtube Video Version
How Angular Pipes Works
Lets first take a look at some of the built-in Angular Pipes so that we can understand how Angular Pipes works.
Angular uppercase Pipe
Angular has a built-in pipe for upper case which can be used to changes all the text into upper case characters. Here is an example
Angular lowercase Pipe
The purpose of lowercase pipe is very simple. It changes all the text into lower case characters. Here is an example
Angular titlecase Pipe
Angular titlecase pipe changes the first letter of each word into upper case. Here is an example
Angular currency Pipe
Angular currency pipe adds the currency symbol with the number. Here is an example
The default currency is USD. But if you want to change the currency you can pass argument to currency pipe and it will change the currency. Here is an example
Angular Custom Pipes First Example
Lets take a look at our example of angular custom pipes. First of all create a new file with the name "my-custom-pipe" and add the following code in it.
Import your custom pipe in your AppModule so it is accessible in our code.
Lets write some code to use our newly created myCustomPipe
If we run our code we will see that the output is empty, but wait a second, we passed "Hello world" to our myCustomPipe then why the output is empty?
To answer this question, we will have to take a look at the "transform" function in our myCustomPipe file which is returning "null" at the moment.
If we want to return the value Hello world then we will have to change our transform function like this.
This will return any value which we pass to our myCustomPipe pipe. So in our case we passing it "Hello world"
Angular Custom Pipes Example Using Arguments
Now lets take a look at an example on how we can pass arguments to our pipe.
In the above example we are applying myCustomPipe on 100 and we are passing two arguments 5 and 10 to it. For instance, lets see how our myCustomPipe will look like.
In our transform function we have three arguments value, param1 and param2. value will contain 100, param1 will contain our first argument of 5 and param2 will contain our second argument of 10.
After that in the next line we are multiplying value with param1 and dividing the whole result with param2. Which will return the result of 50 in our html code.
In conclusion, We have learned how Angular custom pipes work and how we can create our own Angular Custom Pipes.
For more information regarding Angular Pipes please visit Angular documentation. Further more, if you have any questions, suggestions or something is not clear, then feel to make a comment and i will do my best to answer you.