天天看點

ionic4 自定義pipe

例子: 有個 需要根據時間轉換成周幾的需求,我們可以用管道過濾自定義pipe實作

1.指令

ionic g pipe pipes/convertWeek
           

生成下面的2個檔案:

ionic4 自定義pipe

2.書寫covert-week.pipe

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
    name: 'convertWeek'
})
export class ConvertWeekPipe implements PipeTransform {

    transform(value: any, args?: any): any {
        if(!value) return value;
        if(typeof value == 'string'){
            value = parseInt(value);
        }
        return  "日一二三四五六".charAt(new Date(value).getDay());
    }
}
           

3. 使用

ionic4 自定義pipe
  • 在test.moudle.ts中聲明中引入自定義pipe
    ionic4 自定義pipe
  • test.page.ts中定義個變量
    ionic4 自定義pipe
  • html頁面中使用
    ionic4 自定義pipe
  • 頁面效果
    ionic4 自定義pipe

自此,大功告成!!!