Skip to main content

Activity 12 Research Angular Pipes

Updated 2 min readMarkdown
Activity 12 Research Angular Pipes

1. Definition of Angular Pipes

Angular Pipes are a way to transform data in templates. They allow you to format, filter, or manipulate data before displaying it to users. Pipes are often used for formatting dates, numbers, strings, and more, making it easier to present data in a user-friendly format.

2. Types of Angular Pipes

A. Built-in Pipes

  • DatePipe: Formats a date value according to locale rules.

  • CurrencyPipe: Formats a number as currency.

  • DecimalPipe: Formats a number as a decimal number.

  • UpperCasePipe: Converts a string to uppercase.

  • LowerCasePipe: Converts a string to lowercase.

  • SlicePipe: Creates a new array or string containing a subset of the original.

Example Code for Built-in Pipes:

DatePipe:

<p>{{ currentDate | date:'fullDate' }}</p>

CurrencyPipe:

<p>{{ amount | currency:'USD':'symbol':'1.2-2' }}</p>

DecimalPipe:

<p>{{ number | number:'1.0-2' }}</p>

UpperCasePipe:

<p>{{ username | uppercase }}</p>

LowerCasePipe:

<p>{{ message | lowercase }}</p>

SlicePipe:

<p>{{ text | slice:0:5 }}</p>

B. Custom Pipes

When built-in pipes don’t meet specific requirements, you can create custom pipes.

Example Code for Custom Pipe:
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'exclaim'
})
export class ExclaimPipe implements PipeTransform {
  transform(value: string): string {
    return value + '!';
  }
}

Usage in Template:

<p>{{ message | exclaim }}</p>

3. Use Cases of Angular Pipes

  • Displaying Formatted Dates: Use DatePipe to present user-friendly date formats in UI.

  • Converting Currency: Use CurrencyPipe to format monetary values based on user locale.

  • Dynamic Text Transformations: Utilize UpperCasePipe and LowerCasePipe to adjust text presentation dynamically.

  • Slicing Data Arrays: Use SlicePipe to limit the displayed items in a list or table.

Using Built-in Pipes:

<div>
  <h1>{{ birthday | date:'longDate' }}</h1>
  <h2>{{ price | currency:'EUR' }}</h2>
  <h3>{{ description | slice:0:20 }}...</h3>
</div>

Creating and Using Custom Pipes:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'reverse'
})
export class ReversePipe implements PipeTransform {
  transform(value: string): string {
    return value.split('').reverse().join('');
  }
}

Usage in Template:

<p>{{ 'Angular' | reverse }}</p>

References:

https://v17.angular.io/guide/pipes-overview

https://angular.dev/guide/templates/pipes

Excellent

2 days late

More from this blog