Taking Things a Step Further

In this lesson, we'll look at what else we can do with pipes.

At this point, you should feel pretty confident with pipes. We’ve looked at a lot of examples for pipes. We’re going to take things a step further by looking at what else we can do with pipes.

Using pipes outside of interpolation

We’re not limited to using pipes in interpolation. We can use it in directives too. There is one slight change we’ll have to make if we want to do so.

In the app.compontent.html template, we’ll add the following:

<p *ngIf="(cost | double) > 3000">Show me!</p>

In this example, we’re using the ngIf directive to toggle the visibility of the <p> element if the cost property is greater than 3000. The value for the cost property is 2000. However, we can use the double pipe to double its value. If we want to use the double pipe, we’ll need to wrap the value with a pair of parentheses. This will tell Angular to run the cost property through the double pipe before running the comparison.

This will result in the <p> element appearing in the template.

Multiple pipes

We can use multiple pipes if we’d like. All we have to do is separate the pipes with another pipe character (|). For example, let’s say we want to use the double and number pipe on the temperature property. Here’s how we would do that:

<p>{{ temperature | double | number: '1.2-2' }}</p>

This will output 50.60. Pipes will run from left to right. The temperature property will run through the double pipe first, followed by the number pipe. Be aware of this, as you may receive an unexpected value if you’re not careful with the order of the pipes.

Here’s the completed code for this lesson:

Get hands-on with 1200+ tech skills courses.