exhtml
1/25/2019 - 6:18 AM

Angular2 Snippets - Pipes

Pipes

  • Used to transform output IN YOUR TEMPLATE

Built-in pipes

  • https://angular.io/api?query=pipe
  • Pass parameters separated by :, chain pipes with |:
    {{ server.started | date: fullDate | uppercase }}
  • Order is important: parsed from left to right, one pipe is applied over the result of the previous pipe

Custom pipes

Example: pipe for shorten a string: ng generate pipe shorten

shorten.pipe.ts

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

@Pipe({ //we need the Pipe decorator, where you specify the name for the pipe
    name: 'shorten'
})
export class ShortenPipe implements PipeTransform {
    transform(value: any, limit: number) { //this class has to have an special method so that it can be used as a pipe. The transform() method receives the value to transform, and a list of optional arguments you can pass to the pipe
        return value.substr(0, limit) + ' ...'; //we always need to return    
    }
}

You need to import it in your app.module to use it, and add-it to declarations:

import { ShortenPipe } from './shorten.pipe';

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

And now you can use it in your template:
{{ server.name | shorten: 10 }}

Async pipes

  • Allows us to handle asynchronous data (observables, promises, etc)

Let's simulate an asynchronous piece of data:

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

In our template:
{{ appStatus | async }}
You don't see anything at the beginning, and the value shows on the page when it's available.