Jerry's Blog

Recording what I learned everyday

View on GitHub


1 July 2019

Angular (18) -- Pipes

by Jerry Zhang

Day 26: Angular Pipes

What are Pipes?

To transform output in the templates.

Use Case: we have a property called username = 'Max', and we display it by ``.

Now, We want to display this name with uppercase, however, we do not want to change the value in the component.

For this case, we can use the uppercase build-in pipe:

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

To display the date:

{{ server.started | date }}

Parameterize Pipes

server.started | date:'fullDate':2

URL: https://angular.io/api?query=pipe

Pipe chain

server.started | date:'fullDate' | uppercase

The order is important.

Create a custom pipe

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

@Pipe({name: 'shorten'})
export class ShortenPipe implements PipeTransform {
  transform(value: any, ...args: any[]): any {
    return value.substr(0, 10);
  }
}

This will return a substring of the first ten characters.

declarations: [
    AppComponent,
    ShortenPipe
  ],
<strong>{{ server.name | shorten }}</strong> |

Add a parameter to our pipes

@Pipe({name: 'shorten'})
export class ShortenPipe implements PipeTransform {
  transform(value: any, limit: number) {
    if (value.length > limit) {
      return value.substr(0, limit) + ' ...';
    }
    return value;
  }
}
<strong>{{ server.name | shorten:5 }}</strong>

Create a filter pipe

ng g p filter
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {

  transform(value: any, filterString: string, propName: string): any {
    if (value.length === 0 || filterString === '') {
      return value;
    }
    const resultArray = [];
    for (const item of value) {
      if (item[propName] === filterString) {
        resultArray.push(item);
      }
    }
    return resultArray;
  }
}

Updating Arrays or Objects does not trigger it.

Change pure to false.

@Pipe({
  name: 'filter',
  pure: false
})
export class FilterPipe implements PipeTransform {

  transform(value: any, filterString: string, propName: string): any {
    if (value.length === 0 || filterString === '') {
      return value;
    }
    const resultArray = [];
    for (const item of value) {
      if (item[propName] === filterString) {
        resultArray.push(item);
      }
    }
    return resultArray;
  }
}

Then, it will reload whenever the array changes.

Asynchronous pipe

appStatus = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('stable');
    }, 2000);
  });
<h2>App Status: </h2>
tags: Angular