例子: 有個 需要根據時間轉換成周幾的需求,我們可以用管道過濾自定義pipe實作
1.指令
ionic g pipe pipes/convertWeek
生成下面的2個檔案:
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. 使用
- 在test.moudle.ts中聲明中引入自定義pipe
- test.page.ts中定義個變量
- html頁面中使用
- 頁面效果
自此,大功告成!!!