天天看點

Angular自定義管道(非原創)

Angular自定義管道

管道的作用就是将原始值進行轉化處理,轉換為所需要的值

  1. 建立sex-reform.pipe.ts檔案
ng g pipe sex-reform
           

2.編輯sex-reform.pipe.ts檔案

import { Pipe, PipeTransform } form '@angular/core'; //引入PipeTransform是為了繼承transform方法


@Pipe({ name: 'sexReform' }) //name屬性值慣用小駝峰是寫法, name的值為html中| 後面的名稱


export class SexReformPipe implements PipeTransform {
    transform(value: string, args?: any): string {
        switch(value){
            case 'male': return '男';
            case 'female': return '女';
            default: return '雌雄同體';
        } 
    }
}
           

3.在module中聲明管道:

declarations:[SexReformPipe]
           

4.使用demo元件中使用自定義管道

// demo.component.ts
export Class DemoComponent {
    sexValue = 'male';
}

// demo.component.html
<span>{{ sexValue | sexReform }}</span>

// 浏覽器輸出
男
           

同@Component({})和@NgModel({})一樣,@Pipe({})代表這是一個管道,裡面定義了一組中繼資料,用來告訴angular這個管道是如何工作的;

每一個自定義管道都需要實作PipeTransform接口, transform方法用來對傳入的值進行一系列處理,最後轉化為需要的值後return即可;

transform()方法參數格式 - transform(value: string, args1: any, args2: any): value為傳入的值(即為需要用此管道處理的值, | 前面的值); args 為傳入的參數(?:代表可選);

html中使用管道格式 - {{ 資料 | 管道名 : 參數1 : 參數2 }}

注:摘自:https://www.cnblogs.com/zero-zm/p/10204248.html

如有侵權,立即删除