Pipes in Angular -Explained — Part: 2

Introduction

This article is part 2 of the previous article of mine Pipes in Angular -Explained. I highly encourage you to read Part 1 of this article. And this part describes the followings

  1. Parameterized Pipes
  2. Pure and Impure Pipes

Parameterized Pipes

We can pass parameters through pipes. We can specify the parameter with a colon symbol.

For example, in the previous part of this article, we have built a custom pipe that will short the long string and only display a few words from the start of the paragraph. At that time we have used a strongly-typed number to specify the number of words that should be displayed at the start of the paragraph.

Let say, for example, we want to allow a user to manually enter the number of words that should be displayed at the start of the paragraph. This is where we can use Parameterized Pipes. The following example(continuing with the custom pipe that we have implemented in part 1) will show how to parameterize a Pipe.

In the ‘shorted.pipe.ts’ file add the following parameter and replace it instead of that strongly-typed number.

shorted.pipe.ts (with arguments)

Now we can pass the parameter with our custom pipe like the following

custom-pipes.component.html (passing a number as a parameter with pipe)

And this will be the output

shorted string

Pure Pipes

The pure pipe is getting called only when Angular detects a change in the value or the parameters passed with a pipe.

  • If the input parameter is the same, will get the same output at that time.
  • We can share a pure pipe across the application without affecting the output result.

Impure Pipes

The impure pipe is getting called every change detection cycle.

  • The output of the function cannot be predicted
  • Cannot be shared across application because it may break the internal logic.

Examples of impure pipes

  1. Async Pipe
  2. JsonPipe

We can define our pipe (while building custom pipes) whether it will be a pure pipe or impure pipe.

defining the pipe pure or not

I highly encourage to read the following blog that will give a clear explanation about Pure and Impure Pipes

Thank you

Thank you very much for spending your time. I hope this article will give you a better explanation of Angular pipes.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Yathusanan Yokarajah

Yathusanan Yokarajah

“An Active Problem solver @ Software Industry”