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. 使用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 }}