8319. Angular - Pipes
Angular and Pipes


Learn how to create and use pipes in Angular application.

1. Pipes

Pipes are useful at transforming data, especially when the same transformation is used throughout the application. Pipes make it easy to add these transformations into your component template.

2. Angular Pipes

Angular includes several pipes to add to your template. You can use them without importing them or add them as directives.

2.1 lowercase

Lowercase: {{ "The Quick Brown Fox Jumped Over The Lazy Dogs" | lowercase }}

Produces:

Lowercase: the quick brown fox jumped over the lazy dogs

2.2 uppercase

Uppercase: {{ "The Quick Brown Fox Jumped Over The Lazy Dogs" | uppercase }}

Produces:

Uppercase: THE QUICK BROWN FOX JUMPED OVER THE LAZY DOGS

2.3 currency

Currency: {{ 2012.55 | currency }}

Produces:

Currency: USD2,012.55

2.4 UK (gbp) pound currency

UK Pound Currency: {{ 2012.55 | currency: 'gbp':true }}

Produces:

UK Pound Currency: £2,012.55

2.5 percent

Percentage: {{ 0.5 | percent }}

Produces:

Percentage: 50%

2.6 date

Date: {{ dt | date }}

Produces:

Date: Jul 12, 2017

2.7 shortdate

Short Date: {{ dt | date:shortdate }}

Produces:

Short Date: Jul 12, 2017

2.8 Special Date Format

Special Date Format: {{ dt | date:'yMMMMEEEEd' }}

Produces:

Special Date Format: Wednesday, July 12, 2017

Predefined Date Formats

Name Format Example
medium yMMMdjms Sep 3, 2010, 12:05:08 PM
short yMdjm 9/3/2010, 12:05 PM
fullDate yMMMMEEEEd Friday, September 3, 2010
longDate yMMMMd September 3, 2010
mediumDate yMMMd Sep 3, 2010
shortDate yMd 9/3/2010
mediumTime jms 12:05:08 PM
shortTime jm 12:05 PM

2.9 json

{{ {customerName: 'Mark', 'address': '2312 welton av 30333'} | json }}

Produces:

{ "customerName": "Mark", "address": "2312 welton av 30333" }

3. Custom Pipes

3.1 Creating Pipe

Generate a custom pipe.

$ ng generate pipe reverse

3.2 Pipe Definition

Edit reverse.pipe.ts, ReversePipe returns the reversed text.

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

@Pipe({
  name: 'reverse'
})

export class ReversePipe implements PipeTransform {
  transform(value: any, args?: any): any {
    let spaces = 0;
    if (args){
      spaces = parseInt(args);
    }
    let reversed = '';
    for (let i=value.length-1;i>=0;i--){
      reversed += value.substring(i, i+1);
      reversed += Array(spaces + 1).join(' ');
    }
    return reversed;
  }
}
  • The class ReversePipe implements the PipeTransform interface as any pipe would.

3.3 Usage in Component

Edit app.component.ts.

import { Component } from '@angular/core';
import { ReversePipe } from './reverse.pipe';

@Component({
  selector: 'app-root',
  template: `
    <p>My name is {{name | reverse}}
    <p>My name is {{name | reverse:5}}
  `,
  styles: []
})

export class AppComponent {
  name: string = 'Johnny';
}

4. References