Understanding Angular Pipes
Pipes are straightforward functions used within template expressions that accept an input value and produce a transformed output.
Consider this example:
In this case, the firstName pipe takes a fullName value and converts it into just the First Name portion. The pipe can be utilized both in HTML templates and TypeScript files as demonstrated below.
Explore the built-in pipes that Angular offers out of the box.
Passing Multiple Arguments to a Pipe
Pipes are not limited to a single argument—they can accept several parameters. Let's build a standalone pipe that generates a string based on the arguments supplied to it.
> ng g pipe user-string --standalone --flat --skip-tests
In this example, the userString pipe expects three arguments. These parameters must be passed in the template expression exactly as illustrated above.
Lifecycle Hooks Within Pipes
Angular pipes support only the OnDestroy lifecycle hook. This allows you to clean up any subscriptions or data held inside the pipe, preventing memory leaks once the pipe instance is destroyed.
For a practical reference, examine the async pipe implementation. It leverages the OnDestroy hook to unsubscribe from all active subscriptions.
Pure vs. Impure Pipes
By default, pipes are marked as pure. This means Angular only invokes the pipe when it detects a pure change—a strict modification—to the input value.
Since pure pipes are memoized, their transform method runs solely when any of the input parameters actually change.
So why would you ever need an impure pipe?
Suppose you have an array of users that a pipe processes, returning a filtered subset of that data.
The filtering occurs on the initial run. But what happens when you push a new user into the array? The pure pipe fails to notice this alteration because the array reference itself has not changed.
One approach is to create a fresh array instance each time a user is added: users = [...users, newUser]
Alternatively, you can switch to an impure pipe.
An impure pipe is not memoized. It runs on every change detection cycle, regardless of whether its inputs have changed.
While impure pipes serve a purpose, caution is advised. A heavy impure pipe can significantly degrade your application's performance.
You can implement your own memoization logic to fine-tune the efficiency of an impure pipe.
