Pure and Impure Pipe in Angular with an Example.
Pipes are simple functions to use in template expressions to accept
an input value and return a transformed value
A pure pipe is a pipe that is stateless and does not depend on any external factors. This means that if we pass the same input to a pure pipe, it will always return the same output. Here is an example of a pure pipe in Angular
In this example, the DoublePipe
is a pure pipe that simply doubles the input value.
if items = [1, 2, 3, 4, 5];
The resulting output will be:
2 4 6 8 10
On the other hand, an impure pipe is a pipe that is stateful and can depend on external factors such as global state or user input. This means that if we pass the same input to an impure pipe, it may not always return the same output. Here is an example of an impure pipe in Angular:
In this example, the SearchPipe
is an impure pipe that filters an array based on a search term. We set the pure
property to false
in the @Pipe
decorator to indicate that this is an impure pipe.
Note that impure pipes can have a negative impact on performance since they may be called frequently. Therefore, it is recommended to use pure pipes whenever possible
The SearchPipe
will filter an array of objects based on a search term. Assuming we have an items
array of objects with a name
property, the SearchPipe
will filter the items based on the search term:
If the user types "apple" in the search field, the resulting output will be:
Apple
Note that the SearchPipe
is an impure pipe, so it will be called every time the search term changes. This may have a negative impact on performance if the array is large. To avoid this, it's recommended to use pure pipes whenever possible.
Output:
Subscribe to my newsletter
Read articles from AKhil kumar Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by