Thursday, April 19, 2018

Angular - Transforming Data with Pipes

Sometimes we need to transform bound properties before it is displayed. Such is the case with formatting dates, currency, decimals, etc. Pipes can be chained.

Built-in Pipes


  • date
  • number, decimal, percent, currency
  • json, slice, etc
The complete list and more information can be found here.

Examples (no parameters):

{{ product.productCode | lowercase }}
<img [src]='product.imageUrl' [title]='product.productName | uppercase'>
{{ product.price | currency | lowercase }}

Examples (with parameters)

NOTE: Parameters are separated by colons

{{ product.price | currency: 'USD' : true : '1.2-2' }}


Custom Pipe

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'myTransform'})
export class MyTransform implements PipeTransform {
     transform(value: string, customParam1: string): string { ... }
}

Add it to your module (i.e. app.module.ts) as shown here:

@NgModule({
imports: ...
declarations: [ AppComponent, MyTransform ],
bootstrap: ...
})

Use it just like the built in pipes

No comments: