Pipes are simple functions to use in template expressions to accept an input value and return a transformed value.
For Example:
Here, the pipe firstName will take a fullName as an input and transform it into a First Name. It can be used both in a html and ts file as shown below.
You can check out some of the built-in pipes that Angular provides.
Multiple Parameters in a pipe
A pipe can have multiple parameters. Let’s create a standalone pipe that will construct a string based on the given parameters.
> ng g pipe user-string --standalone --flat --skip-tests
Here, userString pipe requires three parameters provided to it. The parameters needs to be provided in the template expression as shown above.
Lifecycle hooks in a pipe
An Angular pipe only supports OnDestroy lifecycle hook. You can clear out any subscription or data that you might use inside the pipe. Just to make sure there is no memory leaks after the pipe’s instance gets destroyed.
For reference, you can check out the implementation of the async pipe. It uses the OnDestroy hook to unsubscribe any subscription.
Pure and Impure Pipes
By default, pipes are defined as pure so that Angular executes the pipe only when it detects a pure change to the input value.
Pure pipes are memoized, this is why the pipe’s transform method only gets called when any of its input parameter is changed.
So, why does impure pipes exist?
Let’s say you have an array of users which gets processed by the pipe and returns a filtered version of the users.
Now, the users will get filtered on the first run. What if you append a new user to the array? The pure pipe won’t detect the change as the user array itself hasn’t changed.
One of the solution for this is creating a brand new instance of the array whenever a new user gets added. i.e users = [...users, newUser]
Or, you can use an impure pipe
An Impure Pipe is not memoized. It gets evaluated on every change detection cycle irrespective of its input value.
While an impure pipe can be useful, be careful using one. A long-running impure pipe could dramatically slow down your application.
You can implement your own memoization procedure to optimize the impure pipe.
Top comments (0)