Angular 前端

Angular 學習筆記(9) — Pipe

JamesW 2024/07/29 08:42:32
223

Pipe 是Angular 實用的工具之一,可以將輸出畫面上的資料套上pipe工具及可格式化,減少重複撰寫轉換的邏輯。

目標:學習使用Angular Pipe

基本使用

參考文章

  • 管道用來對字串、貨幣金額、日期和其他顯示資料進行轉換和格式化:

 

  • Pipe 還有更多不同的使用方式:

 

更多pipe使用:https://angular.io/api?query=pipe

  • 使用多個pipe時,pipe會一組一組的轉譯:

 

自定義Pipe

  • 新增pipe並自訂義內容:

 

  • 使套入的pipe即可:

 

進階定義Pipe

  • 加入動態參數

 

:冒號輸入參數即可

Filter pipe

  • 模擬輸入搜尋功能:

 

  • Pipe 接上對應的欄位:

 

  • 輸入匡輸出對應條件的結果:

 

非同步pipe

  • 非同步pipe 使用 | async,可以偵測非同步Observable內容:
/** component.html **/
<div
*ngIf="items$ | async as items">

<span class="message">
{{ items }} // 使用的非同步內容
</span>
</div>
/** component.ts **/

// 命名後方有加入“$”為Observable
items$ = new Observable<string>((observer: Observer<string>) => {
setInterval(() => observer.next(new Date().toString()), 1000);
});

結語

pipe 是簡單又方便格式統一的工具,只要套好Angular提供、或是自定義的pipe即可共用相同規格的輸出。

JamesW