Angular2 - Starter - Pipes, Custom Pipes

在Angular2 模板中,我们在显示数据时,可以使用通道将数据转换成相应的格式的值的形式来显示,而且这不改变源数据。比如,我们可以使用date通道来转换时间显示的格式: {{date | date:'yyyy-MM-dd'}} ,(1) 以下是Angular提供的基本的通道.

Basic Pipes
Pipe Name Usage Parameters or Effection
currency {{test.currency | currency }}

1234569678 > USD1,234,569,678.00

date {{test.date | date:'yyyy-MM-dd'}}

date:'mediumDate',//Jan,9,2017

date:'shortTime',//9:36 pm

json {{test.json | json }}
[object Object] > {
  "name": "test",
  "title": "Test Pipes"
} //with json pipe
uppercase {{test.str | uppercase }}  hello pipes > HELLO PIPES
lowercase {{test.str1 | lowercase }}  Hello > hello
percent {{test.percent | percent:'.3' }} percent:'.3'//0.25 > 25.000% 
number {{test.decimal | number:'5.1-2' }} number:'5.1-3'//23440.0987 > 23,440.099

 

(2) 以下自定义了一转换电话号码指定数位尾号之外的数字的Pipe, +008615527370515 > ***********70515

//tail-number-length.pipe.ts
import { Pipe,PipeTransform } from '@angular/core'; @Pipe({ //通道名称 name:'tailNumberLength', pure:false }) export class TailNumberLengthPipe implements PipeTransform{ transform(value: string, length:number): any { //对源数据的转换方法 let tailNumberLength = (length === undefined ? 4 : length); let prefixLength = value.length - tailNumberLength; let target = ''; for(let index = 0;index < prefixLength; ++index){ target += '*'; } target += value.substr(prefixLength); return target; } }

  

//tail-number-length.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { TailNumberLengthPipe } from './tail-number-length.pipe'; 构建一个NgModule装饰的TailNumberPipeModule @NgModule({ declarations:[ //引入TailNumberLengthPipe TailNumberLengthPipe ], imports:[ CommonModule ], exports:[ TailNumberLengthPipe ] }) export class TailNumberPipeModule{};

 

appComponent.module.ts
@NgModule({ bootstrap: [ AppComponent ], imports: [ // import custom modules TailNumberPipeModule ] })

 

{{person.phone | tailNumberLength:5}}//+008615527370515 > ***********70515

  

 

posted @ 2017-01-09 21:55  王仲春  阅读(420)  评论(0编辑  收藏  举报