Angular 2 – Using pipes to transform output and making http requests

Pipes are about transforming output

Using Pipes

  • Some pipes are coming built in in Angular:
          {{ server.instanceType | uppercase }} |
          {{ server.started | date}}

Parametrizing pipes

{{ server.started | date:’fullDate’ }}

Where to learn more about pipes

https://angular.io/docs/ts/latest/api/#!?query=pipe

  • For example , for the date pipe we can see all the options we have available:
    • 'medium': equivalent to 'yMMMdjms' (e.g. Sep 3, 2010, 12:05:08 PM for en-US)
    • 'short': equivalent to 'yMdjm' (e.g. 9/3/2010, 12:05 PM for en-US)
    • 'fullDate': equivalent to 'yMMMMEEEEd' (e.g. Friday, September 3, 2010 for en-US)
    • 'longDate': equivalent to 'yMMMMd' (e.g. September 3, 2010 for en-US)
    • 'mediumDate': equivalent to 'yMMMd' (e.g. Sep 3, 2010 for en-US)
    • 'shortDate': equivalent to 'yMd' (e.g. 9/3/2010 for en-US)
    • 'mediumTime': equivalent to 'jms' (e.g. 12:05:08 PM for en-US)
    • 'shortTime': equivalent to 'jm' (e.g. 12:05 PM for en-US)

Chaining multiple pipes

  • {{ server.started | date:'fullDate' | uppercase }}

    The order is important because the types couldnt be the same.

Creating a custom pipe

shorten.pipe.ts

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

@Pipe({
  name: 'shorten'
})
export class ShortenPipe implements PipeTransform{
  transform(value: any) {
    if(value.length > 10) {
      return value.substring(0, 10) + '...';
    } else {
      return value.substring(0, 10);
    }
  }
}

app.component.html

          <strong>{{ server.name | shorten}}</strong> |

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    ShortenPipe
  ],

Parametrizing a custom pipe

shorten.pipe.ts

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

@Pipe({
  name: 'shorten'
})
export class ShortenPipe implements PipeTransform{
  transform(value: any, limit: number) {
    if(value.length > limit) {
      return value.substring(0, limit) + '...';
    } else {
      return value;
    }
  }
}

app.component.html

          <strong>{{ server.name | shorten:15}}</strong> |

 

Example: creating a filter pipe

  • Lets filter the server listing by status by typing in a status input field.

myfilter.pipe.ts

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

@Pipe({
  name: 'myfilter'
})
export class MyfilterPipe implements PipeTransform {

  transform(value: any, filterString: any, 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;
  }

}

app.component.html

<li
          class="list-group-item"
          *ngFor="let server of servers | myfilter:filteredStatus:'status'"
          [ngClass]="getStatusClasses(server)">

Pure and impure pipes

  • If we add servers on a filtered list , we won’t see the added servers at the beginning.
  • That is because filters are pure by default.
  • If we want to make filtering to recalculate on adding servers to the list, we need to specify in the annotation the pure attribute:

myfilter.pipe.ts

@Pipe({
  name: 'myfilter',
  pure: false
})

app.component.html

<button type="button" (click)="addServer()">Add Server</button>

app.component.ts

  addServer(){
    this.servers.push({
      instanceType: 'small',
      name: 'JAJAJAJ',
      status: 'stable',
      started: new Date(15, 1, 2017)
    });
  }

NOTE: We can have performance issue by using this option in large lists

Understanding the async pipe

  • Imagine we have values on the template that depends of async services.
  • Then we can tell Angular to convert Promises in strings when promises are resolved with the async pipe.

app.component.ts

  appStatus = new Promise((resolve,reject)=> {
    setTimeout(
      ()=> {
        resolve('stable');
      }
    ,2000);
  });

app.component.html

<h3>App status: {{ appStatus | async}}</h3>

* We see how app status is blank at the beginning , but after two seconds render ‘stable’

 
dd
f
df
dfd
fd
fd