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>


免責聲明!

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



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