Angular Pipes
Angular Pipes are a key feature in Angular, providing a way to transform data in templates. Essentially, pipes are simple functions that accept an input value and return a transformed value. They are used within template expressions to apply these transformations directly in the template.
Types of Pipes
Angular provides several built-in pipes, and developers can also create custom pipes. The built-in pipes include:
DatePipe:-- Formats a date value according to locale rules.
UpperCasePipe and LowerCasePipe:-- Transforms text to uppercase or lowercase.
CurrencyPipe:-- Transforms a number to a currency string, formatted according to locale rules.
DecimalPipe:-- Transforms a number into a string with a decimal point, formatted according to locale rules.
PercentPipe:-- Transforms a number to a percentage string.
JsonPipe:-- Converts a value into its JSON-format string representation.
SlicePipe:-- Creates a new array or string containing a subset (slice) of the elements.
AsyncPipe:-- Unwraps a value from an asynchronous primitive such as a Promise or Observable.
KeyValuePipe:-- Converts an object or map into an array of key-value pairs.
NumberPipe:-- (alias of DecimalPipe): Transforms a number into a string with a decimal point.
TitleCasePipe:-- Transforms text to title case (first letter of each word capitalized).
I18nPluralPipe:-- Transforms a number into a string based on a mapping object.
I18nSelectPipe:-- Transforms a string into another string based on a mapping object.
SlicePipe:-- Creates a new array or string containing a portion (slice) of the original array or string.
Syntax
The pipe operator (|
) is used within template expressions to apply a pipe to an input value. Here’s the basic syntax:
{{ value | pipeName:argument1:argument2:... }}
value
: The input value to be transformed.pipeName
: The name of the pipe.argument1
,argument2
, ...: Arguments that can be passed to the pipe.
Examples of Using Pipes
Formatting Dates:--
<div>{{ currentDate | date:'fullDate' }}</div>
This uses
DatePipe
to formatcurrentDate
to a full date format.Transforming Text:--
<div>{{ message | uppercase }}</div>
Converts
message
to uppercase usingUpperCasePipe
.Number and Currency Formatting:--
<div>{{ amount | currency:'USD':true }}</div>
Formats
amount
as a currency string in US dollars.Chaining Pipes:-- Pipes can be chained to combine their effects.
<div>{{ (amount | currency:'EUR') | lowercase }}</div>
Formats
amount
as a currency string in euros and then converts it to lowercase.Using with *ngFor and SlicePipe:--
<div *ngFor="let item of items | slice:0:5">{{ item }}</div>
Displays only the first 5 items of the
items
array.
More examples by pipe name
DatePipe: Formats a date value according to locale rules.
<div>{{ currentDate | date:'fullDate' }}</div>
UpperCasePipe: Transforms text to uppercase.
<div>{{ 'hello world' | uppercase }}</div>
LowerCasePipe: Transforms text to lowercase.
<div>{{ 'HELLO WORLD' | lowercase }}</div>
CurrencyPipe: Transforms a number to a currency string.
<div>{{ 150 | currency:'USD':'symbol':'4.2-2' }}</div>
DecimalPipe: Transforms a number into a decimal string.
<div>{{ 123.456789 | number:'3.1-2' }}</div>
PercentPipe: Transforms a number into a percentage string.
<div>{{ 0.75 | percent:'2.0-0' }}</div>
JsonPipe: Converts an object or array into a JSON-formatted string.
<div>{{ {name: 'John', age: 30} | json }}</div>
SlicePipe: Creates a new array or string containing a subset of the elements.
<div>{{ [1, 2, 3, 4, 5] | slice:0:3 }}</div>
AsyncPipe: Unwraps a value from an asynchronous primitive.
<div>{{ asyncData | async }}</div>
KeyValuePipe: Converts an object or map into an array of key-value pairs.
<div *ngFor="let item of object | keyValue">
{{item.key}}:{{item.value}}
</div>NumberPipe: (Alias of
DecimalPipe
): Transforms a number into a string with a decimal point.<div>{{ 98765.4321 | number }}</div>
TitleCasePipe: Transforms text to title case.
<div>{{ 'angular pipes example' | titlecase }}</div>
I18nPluralPipe: Transforms a number into a string based on a mapping object.
<div>{{ count | i18nPlural:mapping }}</div>
In the component:
count = 1;
mapping: {[k: string]: string} = {'=0': 'No items', '=1': 'One item', 'other': '# items'};I18nSelectPipe: Transforms a string into another string based on a mapping object.
<div>{{ gender | i18nSelect: genderMapping }}</div>
In the component:
gender = 'male';
genderMapping: {[k: string]: string} = {male: 'He', female: 'She', other: 'They'};
Creating Custom Pipes
You can create custom pipes to encapsulate any transformation logic that is not covered by Angular’s built-in pipes. Custom pipes are defined by decorating a class with @Pipe
, and the class must implement the PipeTransform
interface.
Best Practices
- Immutability:-- Pipes should be pure and not change the input data.
- Performance:-- Since pipes are called often during the change detection cycle, their operations should be efficient.
- Single Responsibility:-- Each pipe should perform one specific task.