2016-03-05 89 views
7

我想向基本angular2管道添加一些附加功能。Angular2在自定義管道中使用基本管道

即。一些額外的格式在貨幣管道上完成。爲此,我想在我的自定義管道的組件代碼中使用現有的管道。

這有什麼辦法可以做到嗎?

@Pipe({name: 'formatCurrency'}) 
export class FormatCurrency implements PipeTransform { 
    transform(value:number, args:string[]) : any { 
    var formatted = value/100; 

    //I would like to use the basic currecy pipe here. 
    ///100 | currency:'EUR':true:'.2' 

    return 'Do some extra things here ' + formatted; 
    } 
} 

回答

14

可以擴展CurrencyPipe,這樣的事情:

export class FormatCurrency extends CurrencyPipe implements PipeTransform { 
    transform(value: any, args: any[]): string { 
    let formatedByCurrencyPipe = super.transform(value, args); 
    let formatedByMe; 
    // do your thing... 
    return formatedByMe; 
    } 
} 

如果你看一下source,這是類似於如何角管工作...


(由加問題作者)

不要忘記導入CurrencyPipe類

import {CurrencyPipe} from 'angular2/common'; 
+0

日Thnx!我添加了導入行到您的答案,必須搜索以找出CurrencyPipe的導入位置。 –

9

或者,你可以注入的CurrencyPipe:

bootstrap(AppComponent, [CurrencyPipe]); 

管:

@Pipe({ 
    name: 'mypipe' 
}) 
export class MyPipe { 
    constructor(private cp: CurrencyPipe) { 
    } 
    transform(value: any, args: any[]) { 
     return this.cp.transform(value, args); 
    } 
} 
+3

我也喜歡這種方式。有沒有另一種方式來CurrencyPipe提供者?將它添加到bootstrap中似乎有點混亂。我嘗試沒有成功如下: @Pipe({ 名: 'formatCurrency', 提供商:[CurrencyPipe], 管道:[CurrencyPipe] }) –

+0

好問題。我認爲你也可以指定[CurrencyPipe]作爲組件的依賴:providers:[CurrencyPipe]。我同意,它太糟糕了,它不適用於管道級別。 – pixelbits