Angular Pipes
Angular pipes are a powerful feature that allows you to transform the values displayed in your Angular templates. They are a simple way to format data directly within your HTML templates without modifying the underlying data in your component class. Angular provides several built-in pipes for common transformations, and you can also create custom pipes to suit your specific needs.
Here are some key details about Angular pipes:
- Built-in Pipes: Angular comes with several built-in pipes that cover common use cases such as formatting dates, numbers, currency, and uppercase/lowercase transformations. Some of the commonly used built-in pipes include
DatePipe
,DecimalPipe
,CurrencyPipe
,UpperCasePipe
, andLowerCasePipe
. - Using Pipes in Templates: You can use pipes directly within your Angular templates by applying them to expressions enclosed in double curly braces (
{{ }}
). For example:
<!-- Using built-in pipes -->
<p>{{ currentDate | date }}</p>
<p>{{ price | currency }}</p>
<p>{{ message | uppercase }}</p>
<!-- Using a custom pipe -->
<p>{{ valueToBeTransformed | customPipe }}</p>
3. Chaining Pipes: You can chain multiple pipes together to perform multiple transformations on the same value. Pipes are applied sequentially from left to right. For example:
<!-- Chaining multiple built-in pipes -->
<p>{{ currentDate | date: 'short' | uppercase }}</p>
4. Parameterized Pipes: Some built-in pipes accept parameters to customize their behavior. For example, the DatePipe
accepts a format string to specify the desired date format. You can pass parameters to pipes by using a colon (:
) followed by the parameter value. For example:
<p>{{ currentDate | date: 'fullDate' }}</p>
5. Async Pipes: Angular also provides an AsyncPipe
, which is used to automatically subscribe to and unsubscribe from an Observable or Promise. It simplifies the process of working with asynchronous data in Angular templates.
<div>{{ asyncData | async }}</div>
6. Creating Custom Pipes: You can create custom pipes to perform specific transformations that are not covered by built-in pipes. To create a custom pipe, you need to implement the PipeTransform
interface and define the transformation logic within the transform()
method.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'customPipe'
})
export class CustomPipe implements PipeTransform {
transform(value: any, ...args: any[]): any {
// Transformation logic here
return transformedValue;
}
}
7. Pipes are Pure by Default: Angular pipes are pure by default, meaning that they are stateless and do not retain any internal state between invocations. This ensures predictable behavior and efficient change detection. However, you can opt out of this behavior by setting the pure
property to false
in the @Pipe
decorator if your pipe needs to maintain state.
Angular pipes are a versatile tool for formatting and transforming data in Angular applications. They offer a convenient way to manipulate data directly within your templates, making your code more readable and maintainable.
Pipes
A pipe takes in data as input and transforms it to a required output. in below practical scenario, you’ll use pipes to transform a component’s date into a human-friendly date.
import { Component } from ‘@angular/core’;
@Component({
selector: ‘app-my-component’,
template: `<p>The component date is {{ birthday | date }}</p>`
})
export class HeroComponent {
birthday = new Date(1988, 3, 15); // April 15, 1988
}
In html we can use,
<p>The converted date is {{ birthday | date }}</p>
Angular available pipes:
Angular comes with a built-in pipes like:
DatePipe
UpperCasePipe
LowerCasePipe
CurrencyPipe
PercentPipe
Pipes which accepts parameters:
A pipe can accept any number of optional parameters to fine-tune its output. To add parameters to a pipe, follow the pipe name with a colon ( : ) and then the parameter value (such as currency:’EUR’). If the pipe accepts multiple parameters, separate the values with colons (such as slice:1:5)
For example:
template: `
<p>The birthday is {{ birthday | date:format }}</p>
More Pipe options:
Currency
The Currency pipe allows to change the format of price numbers in different currencies:
{{ price | currency:’CAD’ }}
{{ price | currency:’USD’:true }}
{{ price | currency:’EUR’:false:3.2-2 }}
‘EUR’ : The first argument is a string with the local currency code.
true/false : The second possible argument is a boolean to show the that will show either the currency symbol, or the currency code. The default is false and shows the currency code.
3.2-2: The third possible is a string in the format of the decimal pipe to format the number.
Date:
{{ DateTime | date:’medium’ }}
{{ DateTime | date:’fullDate’ }}
{{ DateTime | date:’yy’ }}
{{ DateTime | date:’Hm’ }}
Decimal:
The Decimal pipe formats decimal values:
{{ decimalValue | number:’4.3-5′ }}
The second parameter is as below:
4.3-5: 4 is for the minimum number of integer digits,
3 is for the minimum number of fraction digits and
5 is for the maximum number of fraction digits.
Json:
The Json pipe is useful for debugging and displays an object as a Json string. It uses JSON.stringify behind the scenes:
{{ dataObject | json }}
LowerCase & UpperCase:
Covert text to either lower case or upper case with the respective pipe:
{{ userName.name | uppercase }}
{{ userName.name | lowercase }}
Percent:
The Percent pipe transforms a number into it’s percentage value:
{{ decimalValue | percent }}
{{ decimalValue | percent:’3.2-3′ }}
The optional argument is a string in the Decimal pipe format.
Recent Comments