Ionic2建立一個自定義pipe實現千分位號
阿新 • • 發佈:2019-01-01
1、在src目錄下建立一個pipe目錄用於存放自定義pipe,然後建立一個pipe
|--src
|--pipe
*****.ts
2、在ts檔案裡面寫pipe的邏輯
import { Pipe, PipeTransform } from '@angular/core';
/*
* Raise the value exponentially
* Takes an exponent argument that defaults to 1.
* Usage:
* value | exponentialStrength:exponent
* Example:
* {{ 2 | exponentialStrength:10}}
* formats to: 1024
* 將number轉換為千分位的字串
*/
@Pipe({name: 'toNumber'})
export class ToNumberPipe implements PipeTransform {
//實現了PipeTransform類,實現transform方法,當html使用了toNumber的管道,會自動呼叫此方法
transform(input:number): string {
//這裡可以帶多個引數,第一個引數預設是原始資料,這裡是指
//amount、total 、debt 、overdue ,見下html程式碼
return input.toString().replace(/\B(?=(\d{3 })+(?!\d))/g, ",");//轉為千分位的正則表示式
}
}
3、在app.modules.ts中import這個ts檔案,然後只需在declarations中宣告。
4、在需要的Html模版中使用(不需要引入)
<ul>
<li>{{professionItem.list[0].amount | toNumber}}輛</li>
<li>{{professionItem.list[0].total | toNumber}}元</li>
<li>{{professionItem.list[0].debt | toNumber }}輛</li>
<li>{{professionItem.list[0].overdue | toNumber}}元</li>
</ul>
這樣就完成了,amount等資料會傳入到transform方法,然後返回的資料展示在li上。