Data Format Currency Pipe Date Pipe Angular

Angular Pipes

黃添賜 Jason Huang 2020/08/04 12:50:31
973

概述

每個網頁在瀏覽時,都是需要將資料回傳至頁面上呈現給使用者觀看,但直接將未經處理的資料呈現給使用者,無法得到良好的使用者體驗(如2020-03-26T01:07:14.111Z),大多數的使用者都是希望看到精簡的資料(例如西元2020年03月26日),此時Angular當中的Pipes就是個非常便於使用的資料格式化工具。

Angular內建Pipes:

  1. CurrencyPipe 貨幣
  2. DatePipe 日期
  3. DecimalPipe 處理小數
  4. PercentPipe 小數點轉百分比
  5. TitleCasePipe 英文字首
  6. UpperCasePipe 英文大寫
  7. LowerCasePipe 英文小寫
  8. JsonPipe JSON格式化
  9. SlicePipe 陣列跟字串
  10. AsyncPipe 自動訂閱(不建議使用)
  11. I18nSelectPipe 依據不同的值回傳不同字串
  12. I18nPluralPipe 依據數量回傳不同字串
  13. KeyValuePipe  主鍵排序

範例

CurrencyPipe 貨幣
{{ value_expression | currency [ : currencyCode(ISO 4217貨幣縮寫) [ : display(顯示方式) [ : digitsInfo(顯示長度) [ : locale(地區) ] ] ] ] }} 

@Component({
  selector: 'app-root',
  template: `<div>{{ Currency | currency : '':'':'0.0-0'}}</div>              
              <div>{{ Currency | currency : 'TWD':'code':'0.0-0'}}</div>
              <div>{{ Currency | currency : '':'symbol':'0.0-2'}}</div>
              <div>{{ Currency | currency : '':'test':'3.0-0'}}</div>`
})
export class AppComponent {
  Currency = 1000.001;
}

結果:

1,000

TWD1,000

$1,000

test1,000

DatePipe 日期

{{ value_expression | date [ : format(格式) [ : timezone(時區) [ : locale(地區) ] ] ] }}

@Component({
  selector: 'app-root',
  template: `<div>{{ date | date : '西元yyyy年MM月dd日'}}</div>
              <div>{{ date | date : 'yyyy/MM/dd aa hh:mm:ss'}}</div>
              <div>{{ date | date : 'yyyy/MM/dd HH:mm:ss'}}</div>
              <div>{{ date | date : 'yyyy/MM/dd aa hh:mm:ss':'+0100'}}</div>`
})
export class AppComponent {
  date = new Date('2019/01/01 13:01:31.555');
}

結果:

西元2019年01月01日
2019/01/01 PM 01:01:31
2019/01/01 13:01:31
2019/01/01 AM 06:01:31

DecimalPipe 處理小數

{{ value_expression | number [ : digitsInfo(顯示長度) [ : locale(地區) ] ] }}

@Component({
  selector: 'app-root',
  template: `<div>{{ num | number : '0.0-0'}}</div>
              <div>{{ num | number }}</div>
              <div>{{ num | number : '3.0-5'}}</div>`
})
export class AppComponent {
  num = 1.85094803492357;
}

結果:

2
1.851
001.85095

PercentPipe 小數點轉百分比

{{ value_expression | percent [ : digitsInfo(顯示長度) [ : locale(地區) ] ] }}

@Component({
  selector: 'app-root',
  template: `<div>{{ num | percent }}</div>
              <div>{{ num | percent : '0.0-1'}}</div>
              <div>{{ num | percent : '3.0-5'}}</div>`
})
export class AppComponent {
  num = 0.87512;
}

結果:

88%
87.5%
087.512%

TitleCasePipe 英文字首、UpperCasePipe 英文大寫、LowerCasePipe 英文小寫

@Component({
  selector: 'app-root',
  template: `<div>{{ text1 | titlecase }}</div>
              <div>{{ text2 | uppercase}}</div>
              <div>{{ text3 | lowercase}}</div>`
})
export class AppComponent {
  text1 = 'tITEL';
  text2 = 'upper';
  text3 = 'LOWER';
}
結果:
 
Titel
UPPER
lower

JsonPipe JSON格式化+混和UpperCase Pipe使用

{{ value_expression | json }}

@Component({
  selector: 'app-root',
  template: `<div>
              <p>未使用JSON Pipe:</p>
              <pre>{{object}}</pre>
              <p>使用JSON Pipe:</p>
              <pre>{{object | json}}</pre>
              <p>使用JSON Pipe + UpperCase Pipe:</p>
              <pre>{{object | json | uppercase}}</pre>
            </div>`
})
export class AppComponent {
  object = { foo: 'bar', baz: 'qux', nested: { xyz: 3, numbers: [1, 2, 3, 4, 5] } };
}

未使用JSON Pipe:

[object Object]

使用JSON Pipe:

{
  "foo": "bar",
  "baz": "qux",
  "nested": {
    "xyz": 3,
    "numbers": [
      1,
      2,
      3,
      4,
      5
    ]
  }
}

使用JSON Pipe + UpperCase Pipe:

{
  "FOO": "BAR",
  "BAZ": "QUX",
  "NESTED": {
    "XYZ": 3,
    "NUMBERS": [
      1,
      2,
      3,
      4,
      5
    ]
  }
}

SlicePipe 陣列跟字串

{{ value_expression | slice : start(起始索引位置) [ : end ](結束索引位置) }}

@Component({
  selector: 'app-root',
  template: `<ul>
  <li *ngFor="let i of collection | slice:startIndex:endIndex">{{i}}</li>
</ul>`
})
export class AppComponent {
  startIndex = 0;
  endIndex = 3;
  collection: string[] = ['a', 'b', 'c', 'd'];
}

結果:

  • a
  • b
  • c

AsyncPipe 自動訂閱

用此方法可以直接把回傳的Observable物件傳到頁面上顯示

{{ obj_expression | async }}

@Component({
  selector: 'my-app',
  template: 
  `<ul>
      <li *ngFor="let product of productList$ | async">{{product.projectName}}</li>
    </ul>`
})
export class AppComponent implements OnInit {
  productList$: Observable<any>;
  constructor(private http: HttpClient){}
  ngOnInit(){
    this.productList$ = this.http.post<any>('url', '').pipe(shareReplay(1));
  }
}

I18nSelectPipe 依據不同的值回傳不同字串

{{ value_expression | i18nSelect : mapping }}

@Component({
  selector: 'app-root',
  template: `<span *ngFor="let item of title">{{item | i18nSelect: titleMap}} </span>`
})
export class AppComponent {
  title: string[] = ['長輩', '平輩', '晚輩'];
  titleMap: any = { 長輩: '鈞安', 平輩: '台安', other: '近好' };
}

結果:鈞安 台安 近好

I18nPluralPipe 依據數量回傳不同字串

{{ value_expression | i18nPlural : pluralMap [ : locale ] }}

可以依陣列長度回傳不同的文字

@Component({
  selector: 'app-root',
  template: `
  <div *ngIf="fish1">{{fish1.length}} fish {{ fish1.length | i18nPlural: countMapping }} swimmming</div>
  <div *ngIf="fish2">{{fish2.length}} fish {{ fish2.length | i18nPlural: countMapping }} swimmming</div>
  `
})
export class AppComponent {
  fish1: any[] = ['fish 1'];
  fish2: any[] = ['fish 1', 'fish 2'];
  countMapping:
    { [k: string]: string } = { '=1': 'is', other: 'are' };
}

結果:

1 fish is swimmming
2 fish are swimmming

KeyValuePipe 主鍵排序

可以將api傳回來的keyValueList重新排序

compareFn回傳小於 0,a會排在b前面

compareFn回傳等於 0,a和b排序不會動

compareFn回傳大於 0,a會排在b後面

@Component({
  selector: 'app-root',
  template: `
  <p>預設排序</p>
  <div *ngFor="let item of object | keyvalue">
    {{item.key}}:{{item.value}}
  </div>
  <p>依名稱排序</p>
  <div *ngFor="let item of object | keyvalue : compareFn">
    {{item.key}}:{{item.value}}
  </div>
  `
})
export class AppComponent {
  object: { [key: number]: string } = { 4: 'Australia', 2: 'Taiwan', 1: 'Japan',  3: 'America',  5: 'Thailand' };
  compareFn(a , b ) {    
    return a.value.localeCompare(b.value);
  }
}

結果:

預設依key值排序

1:Japan
2:Taiwan
3:America
4:Australia
5:Thailand

依文字排序

3:America
4:Australia
2:Japan
1:Taiwan
5:Thailand

資料參考:

Angular https://angular.io/

全端開發人員天梯 https://wellwind.idv.tw/blog/2018/11/11/mastering-angular-27-async-pipe/

CK's NotePad https://blog.kevinyang.net/2020/02/13/angular-keyvaluepipe/

CLDR http://cldr.unicode.org/index/cldr-spec/plural-rules

黃添賜 Jason Huang