Angular Pipe 管道元件

  • AsyncPipe:從非同步原語中解開一個值。
  • CurrencyPipe:將數字轉換為貨幣字串,並根據確定群組大小和分隔符號、小數點字元和其他特定於區域設定的配置的區域設定規則進行格式化。
  • DatePipe:根據區域設定規則格式化日期值。
  • DecimalPipe:根據數字選項和區域設定規則格式化值。區域設定決定群組大小和分隔符號、小數點字元以及其他特定於區域設定的配置。
  • JsonPipe:將值轉換為 JSON 格式的表示形式。對於調試很有用。
  • KeyValuePipe:將物件或映射轉換為鍵值對的陣列。
  • LowerCasePipe:將文字轉換為全部小寫。
  • PercentPipe:將數字轉換為百分比字串,並根據確定群組大小和分隔符號、小數點字元和其他特定於語言環境的配置的語言環境規則進行格式化。
  • SlicePipe:建立一個包含元素子集(切片)的新陣列或字串。
  • TitleCasePipe:將文字轉換為標題大小寫。將每個單字的首字母大寫,並將其餘部分轉換為小寫。單字由任何空白字元(如空格、製表符或換行符)分隔。
  • UpperCasePipe:將文字轉換為全部大寫。

AsyncPip從非同步原語中解開一個值。

非同步管道訂閱 ObservablePromise 並傳回其發出的最新值。當發出新值時,非同步管道會標記要檢查變更的元件。當組件被銷毀時,非同步管道會自動取消訂閱以避免潛在的記憶體洩漏。當表達式的參考發生變化時,非同步管道會自動取消訂閱舊的 Observable 或 Promise,並訂閱新的。
This example binds a Promise to the view. Clicking the Resolve button resolves the promise.
此範例將 Promise 綁定到視圖。點擊“解決”按鈕即可解決該承諾。
參考AsyncPipe官網

引入AsyncPipe

1
{{ obj_expression | async }}

example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { AsyncPipe } from '@angular/common';
@Component({
selector: 'async-promise-pipe',
template: `<div>
<code>promise|async</code>:
<button (click)="clicked()">{{ arrived ? 'Reset' : 'Resolve' }}</button>
<span>Wait for it... {{ greeting | async }}</span>
</div>`,
})
export class AsyncPromisePipeComponent {
greeting: Promise<string> | null = null;
arrived: boolean = false;

private resolve: Function | null = null;

constructor() {
this.reset();
}

reset() {
this.arrived = false;
this.greeting = new Promise<string>((resolve, reject) => {
this.resolve = resolve;
});
}

clicked() {
if (this.arrived) {
this.reset();
} else {
this.resolve!('hi there!');
this.arrived = true;
}
}
}

也可以將非同步與 Observable 一起使用。下面的範例將時間 Observable 綁定到視圖。 Observable 使用目前時間不斷更新視圖。

1
2
3
4
5
6
7
8
9
10
11
12
13
import { AsyncPipe } from '@angular/common';
import { Observable, Observer } from 'rxjs';

@Component({
selector: 'async-observable-pipe',
template: '<div><code>observable|async</code>: Time: {{ time | async }}</div>',
})

export class AsyncObservablePipeComponent {
time = new Observable<string>((observer: Observer<string>) => {
setInterval(() => observer.next(new Date().toString()), 1000);
});
}

大寫 DatePipe:uppercase,小寫 LowerCasePipe:lowercase,首字大寫 TitleCasePipe:titlecase

大寫 引入UpperCasePipe import { UpperCasePipe } from '@angular/common';
1
2
3
// html
<p>{{'Hello World' | uppercase}}</p>

HELLO WORLD

小寫
引入LowerCasePipe
import { LowerCasePipe } from ‘@angular/common’;

1
2
3
// html
<p>{{'Hello World' | lowercase}}</p>

hello world
首字大寫
引入TitleCasePipe
import { TitleCasePipe } from ‘@angular/common’;

1
<p>{{ 'some string' | titlecase }}</p>

日期 DatePipe

根據區域設定規則格式化日期值。

參考DatePipePipe官網

引入UpperCasePipe
import { DatePipe } from ‘@angular/common’;

1
{{ value_expression | date [ : format [ : timezone [ : locale ] ] ] }}

ts檔案中新增以下設定

1
2
3
4
5
6
7
8
9
10
11
+ import { DatePipe} from '@angular/common';

@Component({
selector: 'app-test-list',
+ imports: [DatePipe],
templateUrl: './test-list.component.html',
styleUrl: './test-list.component.scss'
})
export class TestListComponent implements OnInit {
now :number= Date.now();
}
| date
html
1
<td>{{now  | date  }} </td> 
顯示:Apr 4, 2025
| date | uppercase
1
<p>{{now | date | uppercase }}</p> 
顯示:APR 4, 2025
| date: 'short':'+0000'
1
<p> {{now | date: 'short':'+0000' }}</p> 
顯示:4/4/25, 6:35 AM
| date:'yyyy-MM-dd HH:mm:ss'
1
<p> {{now |  date:'yyyy-MM-dd HH:mm:ss' }}</p> 
顯示:2025-04-04 06:35:34
| date: 'short'
1
<p> {{now | date: 'short' }}</p> 
顯示:4/4/25, 2:35 PM
| date: 'medium'
1
<p> {{now | date: 'medium' }}</p> 
顯示:Apr 4, 2025, 2:35:34 PM
| date: 'long'
1
<p> {{now | date: 'long' }}</p> 
顯示:April 4, 2025 at 2:35:34 PM GMT+8
| date: 'full'
1
<p> {{now | date: 'full' }}</p> 
顯示:Friday, April 4, 2025 at 2:35:34 PM GMT+08:00

貨幣 (CurrencyPipe)

將數字轉換為貨幣字串,並根據確定群組大小和分隔符號、小數點字元和其他特定於區域設定的配置的區域設定規則進行格式化。
CurrencyPipe公式

1
{{ value_expression | currency [ : currencyCode [ : display [ : digitsInfo [ : locale ] ] ] ] }}
引入UpperCasePipe import { CurrencyPipe } from '@angular/common';
1
2
3
4
5
6
7
8
9
10
11
+ import {  CurrencyPip} from '@angular/common';

@Component({
selector: 'app-test-list',
+ imports: [ CurrencyPip],
templateUrl: './test-list.component.html',
styleUrl: './test-list.component.scss'
})
export class TestListComponent implements OnInit {
}

| currency
html
1
<p> {{50000 | currency}}</p>
顯示:$50,000.00
| currency:'TWD':true
html
1
<p> {{50000 | currency:'TWD':true}}</p> 
顯示:NT$50,000.00
| currency:'TWD':'TWD'
html
1
<p> {{50000 | TWD50,000.00}}</p> 
顯示:TWD50,000.00
| currency:'TWD':'TWD':'4.1-3'
digitsInfo:數字顯示方式 (String)
  • minIntegerDigits:小數點前的最小整數位數。默認值為1
  • minFractionDigits:小數點後的最少位數。默認值為2
  • maxFractionDigits:小數點後的最大位數。默認值為2
html
1
<p>{{987.1234 | currency:'TWD':'TWD':'4.1-3'}}</p>
顯示:TWD0,987.123
1
2
3
4
<p>{{ 0.259 | currency: 'CAD' }}</p>
<p>{{ 1.3495 | currency: 'CAD' }}</p>
<p> {{ 0.259 | currency: 'CAD' : 'code' }}</p>
<p> {{ 1.3495| currency: 'CAD' : 'symbol' : '4.2-2' }}</p>

SlicePip

建立一個包含元素子集(切片)的新陣列或字串。
參考官網SlicePip資料

引入SlicePipe
import { SlicePipe } from ‘@angular/common’;

1
2
3
4
5
6
7
8
9
10
+ import {SlicePipe} from '@angular/common';
@Component({
selector: 'app-test-list',
+ imports: [ SlicePipe],
templateUrl: './test-list.component.html',
styleUrl: './test-list.component.scss'
})
export class TestListComponent implements OnInit {
collection: string[] = ['a', 'b', 'c', 'd'];
}

使用公式

1
{{ value_expression | slice : start [ : end ] }}

html

1
2
3
<ul>
<li *ngFor="let i of collection | slice: 1 : 3">{{ i }}</li>
</ul>

顯示:

  • b
  • c

DecimalPipe

根據數字選項和區域設定規則格式化值。區域設定決定群組大小和分隔符號、小數點字元以及其他特定於區域設定的配置

參考官網DecimalPipe資料

1
2
3
4
5
6
7
8
9
10
+ import {DecimalPipe} from '@angular/common';
@Component({
selector: 'app-test-list',
+ imports: [DecimalPipe],
templateUrl: './test-list.component.html',
styleUrl: './test-list.component.scss'
})
export class TestListComponent implements OnInit {
testNumber:number=3.14159;
}

html

1
<p>{{ testNumber| number  }}</p>

顯示:3.141

小數點建議定義參數後 .toFixed(5)

1
2
3
testNumber:number=3.14159;

{{ testNumber.toFixed(5) }}

自定義 Pipe

  • 新增pipe 功能ts名稱
    • 引入:Pipe, PipeTransform
    • @Pipe({名稱:功能})
    • export class FormatTaiwanYearPipe implements PipeTransform
    • transform(date: number | any) {.... return ....}
ˊ

範例:民國年

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
name: 'TaiwanYear'
})

export class FormatTaiwanYearPipe implements PipeTransform {
transform(date: number | any) {
let d = new Date(date),
year = d.getFullYear() - 1911,
month = (d.getMonth()+1 < 10 ? '0'+(d.getMonth()+1) : d.getMonth()+1) ,
day = (d.getDate()< 10 ?'0'+d.getDate():d.getDate()),
hour=(d.getHours()<10?'0'+d.getHours():d.getHours()) ,
minutes = (d.getMinutes()<10?'0'+d.getMinutes():d.getMinutes())

return [year, month, day].join('-')+' '+ [hour,minutes].join(':');
}
}

頁面使用

  • 引入類名稱
1
2
3
4
5
6
7
8
9
import { FormatTaiwanYearPipe } from '存放位址';

@Component({
imports: [FormatTaiwanYearPipe],
})

export class TestListComponent implements OnInit {
nowTimeStamp:number =Date.now()
}
1
2
3
4
<p >
{{ nowTimeStamp | TaiwanYear }}
</p>

github