Angular pipes are simple functions that are used to transform or format data in templates. They allow you to modify, filter, and format data in the template without modifying the component. Pipes are easy to integrate into a template using the pipe (|) character.
The main purpose of Angular pipes is:
1. To transform data into a readable format for users.
2. To keep the component code clean and focused on the logic only.
3. To improve code reusability by allowing you to use the same pipe in multiple components.
There are several built-in pipes in Angular, such as ‘uppercase‘, ‘lowercase‘, ‘date‘, ‘number‘, ‘currency‘, ‘percent‘, and ‘json‘. Let’s consider an example of the ‘date‘ pipe, which is used to format a date value.
Suppose you have a date object in TypeScript like:
export class AppComponent {
currentDate: Date = new Date();
}
In your template, you can apply the ‘date‘ pipe to format the ‘currentDate‘ value as follows:
<p>The current date is: {{ currentDate | date }}</p>
By default, the ‘date‘ pipe formats the value to look like "Jun 15, 2021", but you can also supply additional arguments for custom formatting. For example, you can use the ‘’short’‘ format:
<p>The current date in short format is: {{ currentDate | date: 'short' }}</p>
This will format the date to look like "6/15/21, 5:08 PM". Note that the format string is case sensitive, and must be enclosed in single or double quotes.
Keep in mind that, while Angular pipes are useful for simple transformations or formatting, they are not recommended for complex operations or heavy processing because they can negatively impact performance. For such cases, it is better to handle the data transformation in the component, using a service or helper functions.