angular2+ 自定義pipe管道實例--定義全局管道及使用


首先到項目目錄下ng g pipe pipe/myslice 就會在app目錄下生成一個pipe文件夾文件夾下有myslice.pipe.ts文件,如果沒有也可以自己手動新建

然后需要再app.module.ts 也就是在模塊文件中設置

// 首先導入
import { MyslicePipe } from '../../pipe/myslice.pipe'

// 然后在相應的declarations中聲明
 declarations: [
    MyslicePipe
  ]

好了就可以安心的在myslice.pipe.ts中自定義需要的管道了

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'myslice'})

export class MyslicePipe implements PipeTransform {
    transform(value: string): string {
    if(!value) return value;
    return decodeURI(value.split('img/')[1]); // 這里的value是傳入的值,返回你想要的結果表達式
  }
    constructor() {
    }
} 

使用和其他管道使用方法一樣

在任意的html文件中都可使用

// detailPage.attachment是個字符串
<span>{{detailPage.attachment | myslice}}</span>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM