Angular2管道在模板和component.ts中的使用

以自定义管道为例区分在模板和组件中的使用

定义管道(pipe.ts)

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

@Pipe({
    name: 'alarmPipe' // 自定义管道名
})
export class AlarmPipePipe implements PipeTransform {
    transform(value: any, args?: any): any {
        let res: string;
        if (value === 1) {
            res = 'TRUE';
        } else if (value === 0) {
            res = 'FALSE';
        } else if (value === -1) {
            res = 'UNVERIFIED';
        } else {
            res = 'OPEN';
        }
        return res;
    }
}

一、在组件中使用管道时

1.首先在组件所在module中提供providers供组件租入使用

component.module.ts

import { AlarmPipePipe } from 'app/alarm-management/alarm-pipe.pipe'; // import自定义组件

@NgModule({
    imports: [
        CommonModule,
        MaterialModule,
        FormsModule,
        ReactiveFormsModule,
        NgZorroAntdModule,
        MatFormFieldModule,
        MatInputModule,
        MatSelectModule,
        SharedModule,
        MultiLayoutModule,
        TranslateModule,
        AlarmMgtRoutingModule
    ],
    providers: [AlarmPipePipe], // provides管道供组件注入使用
    declarations: [AlarmMgtComponent]
})
export class AlarmMgtModule {}

2.在component.ts中使用

import { AlarmPipePipe } from 'app/alarm-management/alarm-pipe.pipe'; // 引入组件

   constructor(
        ....
        private alarmPipe: AlarmPipePipe // 注入自定义组件
    ) {
    }


test() {
   this.alarmPipe.transform(1) // 使用管道 ‘TRUE’
}

二、在模板中使用

// component.html

<td>
{{1 | alarmPipe}} // ‘TRUE’
</td>
原文地址:https://www.cnblogs.com/yuanchao-blog/p/13254889.html