2016-01-27 41 views

回答

14

是的,您可以使用PLATFORM_PIPES添加一个自定义管道并命名为管道date来劫持它。

@Pipe({ 
    name : 'date' // Hijacks the 'date' pipe 
}) 
class CustomDatePipe { 
    transform(val, args) { 
    return /* do something new with the value */; 
    } 
} 

@Component({ 
    selector: 'my-app', 
    template : '{{mydate | date}}', 
}) 
export class App { 
    mydate = Date.now(); 
} 

// Provides the CustomDatePipe globally 
bootstrap(App, [provide(PLATFORM_PIPES, {useValue: [CustomDatePipe], multi: true})]); 

这样你不必每次都在组件中的pipes属性中指定它。

这是一个plnkr与一个例子工作。

+0

您是否知道需要做什么以便管道在单元测试中也是全局可用的? –

2

是,使用PLATFORM_PIPES以下列方式

https://angular.io/docs/ts/latest/api/core/index/PLATFORM_PIPES-let.html

import {PLATFORM_PIPES} from '@angular/core'; 
import {OtherPipe} from './myPipe'; 
@Component({ 
    selector: 'my-component', 
    template: ` 
    {{123 | other-pipe}} 
    ` 
}) 
export class MyComponent { 
    ... 
} 
bootstrap(MyComponent, [{provide: PLATFORM_PIPES, useValue: [OtherPipe], multi:true}]); 
1

埃里克·马丁内斯的回答工作正常!请记住,PLATFORM_PIPES在Angular4中已弃用。 Angular4中的平台管道通过app.modules进行配置:

/** 
* `AppModule` 
*/ 
@NgModule({ 
    ... 
    providers: [ 
     ... 
     CustomDatePipe 
    ] 
}) 
+0

为了测试(回答Vilmantas Baranauskas的问题):你可以为管道本身编写一个测试,并在你的测试中明确地调用变换,例如新的CustomDatePipe()。transform(输入) –

相关问题