Angular Pipes: Transforming Data in Your Templates
Angular Pipes are functions that transform data directly within your templates, making your application more dynamic and user-friendly by formatting data, transforming strings, and filtering data.
Angular Pipes are a powerful feature that allows you to transform data directly within your templates. They act as filters, manipulating data before it's displayed to the user, making your application more dynamic and user-friendly.
Understanding Angular Pipes
Definition: Angular Pipes are functions that take input data and transform it into a desired output. They are similar to filters in other programming languages, but offer more flexibility and customization options.
Purpose: Pipes are used to:
Format data: Display dates, numbers, and currencies in a user-friendly format.
Transform strings: Convert text to uppercase, lowercase, or title case.
Filter data: Select specific elements from an array or string based on criteria.
Types of Angular Pipes:
DatePipe: Formats dates based on locale rules. You can specify a format string to control the output, such as
shortDate
,mediumDate
, or a custom format likedd/MM/yyyy
.CurrencyPipe: Formats currency values with a currency symbol, thousands separator, and decimal separator. You can specify the currency code (e.g.,
USD
,EUR
) and optional display options likesymbol
,symbol-narrow
, orcode
.DecimalPipe: Formats decimal numbers with a specific number of decimal places. The format string takes the form
"{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}"
.UpperCasePipe: Converts text to uppercase.
LowerCasePipe: Converts text to lowercase.
SlicePipe: Extracts a portion of an array or string. You can specify the start and end indices of the slice. Negative indices indicate an offset from the end of the array.
PercentPipe: Formats a number as a percentage. You can optionally specify a format string similar to the
DecimalPipe
.JsonPipe: Converts a JavaScript object into a JSON string.
AsyncPipe: Used to subscribe to Observables and Promises. It automatically unsubscribes when the component is destroyed, preventing memory leaks.
Built-in Pipes
Angular provides a set of built-in pipes for common transformations. Here are some examples:
DatePipe: Formats dates according to locale rules.
<p>Today's date is: {{ today | date: 'shortDate' }}</p> ``` [[10]](https://medium.com/@izeey/exploring-angular-pipes-a-comprehensive-guide-b17529c11daa) **CurrencyPipe:\* Formats currency values with a currency symbol, thousands separator, and decimal separator. ```html <p>The price is: {{ price | currency: 'USD' }}</p> ``` [[12]](https://medium.com/@cubensquare/what-are-angular-pipes-5e3a2594cda5) **DecimalPipe:\* Formats decimal values with a specific number of decimal places. ```html <p>The total cost is: {{ totalCost | number: '1.2-2' }}</p> ``` [[12]](https://medium.com/@cubensquare/what-are-angular-pipes-5e3a2594cda5) **UpperCasePipe:\* Converts text to uppercase. ```html <p>The title is: {{ title | uppercase }}</p> ``` [[12]](https://medium.com/@cubensquare/what-are-angular-pipes-5e3a2594cda5) **LowerCasePipe:\* Converts text to lowercase. ```html <p>The message is: {{ message | lowercase }}</p> ``` [[12]](https://medium.com/@cubensquare/what-are-angular-pipes-5e3a2594cda5) **SlicePipe:\* Extracts a portion of an array or string. ```html <p>The first three letters are: {{ text | slice: 0:3 }}</p> ``` [[10]](https://medium.com/@izeey/exploring-angular-pipes-a-comprehensive-guide-b17529c11daa) ### Creating Custom Pipes When the built-in pipes don't meet your specific needs, you can create your own custom pipes. This allows you to perform any data transformation you require. Example: A custom pipe to reverse a string: ```typescript import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'reverse' }) export class ReversePipe implements PipeTransform { transform(value: string): string { return value.split('').reverse().join(''); } } ``` [[15]](https://www.digitalocean.com/community/tutorials/angular-custom-pipes-angular) ### Use Cases of Angular Pipes Here are some practical use cases for Angular Pipes: **Displaying formatted dates:\* Use
DatePipe
to display dates in a user-friendly format, like "March 10, 2023" or "10/03/2023". **Converting text to uppercase:\* UseUpperCasePipe
to display titles or headings in uppercase. **Formatting currency values:\* UseCurrencyPipe
to display prices in the correct currency format, including the currency symbol. **Filtering data:\* Use custom pipes to filter data based on specific criteria, like displaying only products with a certain price range. **Dynamic data transformation:\* Use pipes to transform data dynamically based on user input or other factors, like displaying a different date format based on the user's locale. ### Code Snippets Built-in Pipes: ```html <!-- Displaying a formatted date --> <p>Today's date is: {{ today | date: 'mediumDate' }}</p> <!-- Displaying a currency value --> <p>The price is: {{ price | currency: 'USD' }}</p> <!-- Displaying a string in uppercase --> <p>The title is: {{ title | uppercase }}</p>
Custom Pipe:
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'highlight' }) export class HighlightPipe implements PipeTransform { transform(value: string, term: string): string { if (!term) { return value; } return value.replace(new RegExp(term, 'gi'), '<span class="highlight">$&</span>'); } }
Links: