Definition of Angular Pipes
Angular Pipes are a way to transform data directly in the template. Pipes are used to format data, such as dates, currency, and strings, without altering the underlying data model. They offer a simple way to display data in a more user-friendly format.
Purpose of Pipes:
Pipes transform the output that is displayed in the template.
They can format values like numbers, strings, dates, and more.
Types of Angular Pipes
DatePipe: Formats a date value.
{{ today | date:'shortDate' }}
CurrencyPipe: Formats a number as a currency string.
{{ amount | currency:'USD' }}
DecimalPipe: Formats a number as decimal with specified decimal places.
{{ 3.14159 | number:'1.2-2' }}
UpperCasePipe: Transforms a string to uppercase.
{{ 'hello world' | uppercase }}
LowerCasePipe: Transforms a string to lowercase.
{{ 'HELLO WORLD' | lowercase }}
SlicePipe: Slices an array or string to display only a part of it.
{{ 'hello world' | slice:0:5 }} Output: hello
Custom Pipes: When built-in pipes do not meet specific requirements, custom pipes can be created.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'reverse'})
export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}
Use Cases of Angular Pipes
DatePipe: Display formatted dates for user interfaces.
<p>{{ user.joinedDate | date:'fullDate' }}</p>
CurrencyPipe: Format numbers as currency when displaying product prices.
<p>Price: {{ product.price | currency:'USD':'symbol' }}</p>
UpperCasePipe/LowerCasePipe: Convert user input to a specific case for consistency.
<p>{{ user.name | uppercase }}</p>
Code Snippets
Using Built-In Pipes:
<!-- DatePipe -->
<p>Today is {{ today | date:'fullDate' }}</p>
<!-- CurrencyPipe -->
<p>Total: {{ 500 | currency:'USD' }}</p>
<!-- UpperCasePipe -->
<p>{{ 'hello world' | uppercase }}</p>
Custom Pipe Example:
<!— typescript—>
@Pipe({name: 'exponentialStrength'})
export class ExponentialStrengthPipe implements PipeTransform { transform(value: number, exponent: string): number {
let exp = parseFloat(exponent);
return Math.pow(value, isNaN(exp) ? 1 : exp);
}
}
<!— html—>
{{ 2 | exponentialStrength:10 }} <!-- Output: 1024 -->
REFERENCES:
Official Angular Pipes Documentation: angular.io/guide/pipes
Article on Angular Pipes Usage: tektutorialshub.com/angular/angular-pipes
Creating Custom Pipes in Angular: angular.io/guide/pipes#custom-pipes