In Angular, pipes are a feature that allows us to transform the data. Using Pipes we can format, filter, and manipulate data. Angular supports several built-in pipes. However, we can also create custom pipes based on our requirements
Key Features:
2. Pipes can be provided with arguments by using the colon (:) sign.
Ex.
Built-in Pipes: Angular comes with several built-in pipes that cover common transformation tasks. Some examples include:
- {{ someDate | date:'longDate' }} — Formats a date as a long date.
- {{ someText | uppercase }} — Converts text to uppercase.
- {{ someNumber | currency:'USD':true }} — Formats a number as currency (USD) with a currency symbol.
PipeTransform interface : The PipeTransform interface is used when we creating custom pipes in Angular.
Ex.
The PipeTransform interface contains a single method: transform. This method is where you define the transformation logic for your custom pipe. It takes two parameters:
- value: This is the input data that you want to transform using the pipe.
- ...args: These are optional parameters that you can use to pass additional information to the pipe.
Pure Pipes vs Impure Pipes : Pure pipes are designed to optimize change detection by only recalculating when the input values or arguments change. If the input values remain the same, the pipe won't run its transform method, reducing unnecessary calculations.
Aspect | Pure Pipes | Impure Pipes |
---|---|---|
Change Detection Optimization | Pure pipes optimize change detection by only recalculating when input values or arguments change. | Impure pipes do not optimize change detection and always recalculate on every change detection cycle. |
Performance | Pure pipes are more efficient for static and predictable data as they avoid unnecessary recalculations. | Impure pipes may lead to more recalculations, impacting performance, especially if used extensively. |
Use Cases | Suitable for deterministic transformations, like formatting, calculations, and filtering, where input data remains unchanged. | Suitable for scenarios involving dynamic data, real-time updates, and side effects, where frequent recalculations are needed. |
Syntax | To define a pure pipe, set the pure property to true in the @Pipe decorator. | Impure pipes are the default behavior when you create a custom pipe without specifying the pure property. |