###### tags: `Angular` # 🥔學習用 Pipe 來改變顯示資料 認識完 Component 的一些小知識後,接著我們來看看如何使用 Pipe 來改變資料的顯示方式,以及為什麼我們要使用 Pipe。 ng g p schPipe ## *Pipe 實作* ### *step1.* 建立Pipe - 依自己的需求來做一支Pipe。 ==*範本*== [StackBlitz-Pipe #phone function: use * hide word](https://stackblitz.com/edit/pipe-phone?file=src/app/app.component.html) ```typescript= import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'hideWordPipe' }) export class HideWordPipe implements PipeTransform { /**顯示末幾碼,其餘*遮罩 * @params value 畫面上的值 * @params viewLen 要顯示末幾碼(預設顯示末三碼) */ transform(value: string, viewLen = 3): any { if (!value) {return null; } const wordLen = value.length; const hideLen = wordLen - viewLen; let viewWord = ''; for (let i = hideLen; i > 0; i--) { viewWord += '*'; } viewWord += value.slice(hideLen); return viewWord; } } ``` ### *step2.* 應用Pipe - 要使用Pipe,必須在範本(HTML)中使用`[param] | [PiepName]`來表示,這邊的`PipeName`是裝飾器內的name。 `.pipe` - `transform(value: string, arg?: any)` ```htmlembedded <span>{{ data | hideWordPipe }}</span> ``` - 若`Pipe`是需要傳值的在範本(HTML)內用`: [arg]`。 `.pipe` - `transform(value: string, arg1: any)` ```htmlembedded <span>{{ data | hideWordPipe:3 }}</span> ``` - 若`Pipe`需要傳多個值,一個值就再多用一個`: [arg]`表示,以此類推...。 `.pipe` - `transform(value: string, arg1: any, arg2: any)` ```htmlembedded <span>{{ data | hideWordPipe:3:3 }}</span> ``` > Pipe 除了字串外,也能作用在陣列上。 ## Pipe 的優點及使用時機 [StackBlitz-diff pipe&function](https://stackblitz.com/edit/angular-ivy-artsx4?file=src/app/name-pipe.pipe.ts) 使用 Pipe 可以更容易在 HTML 裡面直接改變資料的顯示方式,雖然有時候直接把控制顯示的邏輯寫到 Component 內比較單純也相較直覺,但 Pipe 在 Angular 的渲染機制下,對於網頁的效能來說是比較好的。
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up