Using Pipes

Like a filter, a pipe also takes data as input and transforms it to the desired output. A basic example of using pipes is shown below:

  1. import { Component } from '@angular/core';
  2. @Component({
  3. selector: 'product-price',
  4. template: `<p>Total price of product is {{ price | currency }}</p>`
  5. })
  6. export class ProductPrice {
  7. price = 100.1234;
  8. }

View Example

Passing Parameters

A pipe can accept optional parameters to modify the output. To pass parameters to a pipe,simply add a colon and the parameter value to the end of the pipe expression:

  1. pipeName: parameterValue

You can also pass multiple parameters this way:

  1. pipeName: parameter1: parameter2
  1. import { Component } from '@angular/core';
  2. @Component({
  3. selector: 'app-root',
  4. template: '<p>Total price of product is {{ price | currency: "CAD": true: "1.2-4" }}</p>'
  5. })
  6. export class AppComponent {
  7. price = 100.123456;
  8. }

View Example

Chaining Pipes

We can chain pipes together to make use of multiple pipes in one expression.

  1. import { Component } from '@angular/core';
  2. @Component({
  3. selector: 'app-root',
  4. template: '<p>Total price of product is {{ price | currency: "CAD": true: "1.2-4" | lowercase }}</p>'
  5. })
  6. export class ProductPrice {
  7. price = 100.123456;
  8. }

View Example

原文: https://angular-2-training-book.rangle.io/handout/pipes/using_pipes.html