In Angular, pipes are used to transform data before displaying it in a template. They can be categorized into two types: pure and impure pipes. Let’s discuss each of them in detail.
**Pure Pipes**
Pure pipes are the default type of pipes in Angular. They are called pure because they do not cause any side effects, and their output depends solely on their input values. In other words, if the input data does not change, the output of the pure pipe remains the same. Due to their pure nature, Angular optimizes pure pipes by memoizing (caching) the results and only re-invoking the pipe when the input changes. As a result, pure pipes are generally more performant than impure pipes.
Use cases for pure pipes:
1. Formatting strings, numbers, or dates. For example, transforming a date into a human-readable format:
‘ someDate | date:’medium’ ‘
2. Converting an array or object into a subset, like filtering an array based on certain conditions:
‘ employeeList | filter:searchText ‘
3. Capitalizing the first letter of a string, like a name or title:
‘ userName | capitalize ‘
**Impure Pipes**
Impure pipes, as the name suggests, can cause side effects and their output may depend on values other than their input. Unlike pure pipes, impure pipes are executed on every change detection cycle, regardless of whether the input has changed or not, leading to a potentially degraded performance if the pipe’s transformation is expensive to compute.
To create an impure pipe, you need to explicitly set the ‘pure‘ property of the ‘Pipe‘ decorator to ‘false‘:
@Pipe({
name: 'mypipe',
pure: false
})
export class MyPipe implements PipeTransform {
transform(value: any): any {
// ...
}
}
Use cases for impure pipes:
1. Real-time data updates, like displaying a timer or live changes in data fetched from an external API.
2. Working with mutable objects, like updating a table or list when their properties change, even if the object reference remains the same.
3. Customizing the behavior of the built-in ‘async‘ pipe. The ‘async‘ pipe is impure and can be customized to handle additional logic when working with observables or promises.
In summary, pure pipes are ideal for data transformations that do not depend on external factors or cause side effects, while impure pipes are suitable for handling real-time data updates, mutable objects, or customizing specific behaviors. However, due to the performance implications of impure pipes, it’s generally recommended to use pure pipes whenever possible and consider other approaches (like Observables with the async pipe) for scenarios where impure pipes might be needed.