【发布时间】:2016-01-27 17:26:13
【问题描述】:
我想覆盖“日期”管道,并像内置管道一样享受全局访问的好处——也就是避免在每个组件注释中导入和使用管道[]数组。这可能吗?
【问题讨论】:
标签: angular
我想覆盖“日期”管道,并像内置管道一样享受全局访问的好处——也就是避免在每个组件注释中导入和使用管道[]数组。这可能吗?
【问题讨论】:
标签: angular
是的,您可以使用 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 ,其中有一个示例。
【讨论】:
Eric Martinez 的回答效果很好!请记住 PLATFORM_PIPES 在 Angular4 中已弃用。 Angular4 中的平台管道是通过 app.modules 配置的:
/**
* `AppModule`
*/
@NgModule({
...
providers: [
...
CustomDatePipe
]
})
【讨论】:
是的,请按以下方式使用 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}]);
【讨论】: