Combine Pipes
Let’s learn about pipe chaining techniques.
We'll cover the following
At this point, we know how to use pipes and implement our own pipes if the built-in pipes are simply not enough. However, there’s more to learn. What should we do if the pipes we have in our codebase contain all the transformation logic we need, but we need to display values as results of multiple pipe transformations?
Chain pipes
There’s a method that allows us to combine multiple pipes together. They create a so-called chain of transformations. Let’s imagine a scenario where we want to display a date in a long, user-friendly format like this:
Friday, June 15, 2022
Additionally, we want to display it all in uppercase, like this:
FRIDAY, June 15, 2022
We already know about the following built-in pipes that can help us with these transformations:
DatePipe
UpperCasePipe
To display the date in user-friendly format with all uppercase letters, we can use the two pipes as presented below, assuming these are two separate transformations:
Here’s the Date transformation:
<p> {{ dateObject | date:'fulldate' }} </p>
Here’s the Case transformation:
<p> {{ 'Friday, June 15, 2022' | uppercase }} </p>
Angular gives us an easy way to combine these two transformations together. To put pipes into a chain, we simply have to put them one after the other. That way, they apply the transformation to the value and pass their output as the input for the next pipe in the chain. Let’s consider the following code:
<p> {{ dateObject | date:'fulldate' | uppercase }} </p>
As we can see, DatePipe
receives a dateObject
that has the date we want to display. The DatePipe
converts it into Friday, June 15, 2022
and UpperCasePipe
automatically picks it up. Finally, UpperCasePipe
transforms the whole date to uppercase letters and returns that to the display.
Here’s the complete live result:
Get hands-on with 1400+ tech skills courses.