是否可以覆盖内置的Angular 2管道,以便它们可以在全球范围内使用?

Ala*_*say 12 angular

我想覆盖"日期"管道并享受全局访问的好处,就像内置管道一样 - 也就是说,避免在每个组件注释中导入和使用pipes []数组.这可能吗?

Eri*_*nez 15

是的,您可以使用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})]);
Run Code Online (Sandbox Code Playgroud)

这样,您不必每次pipes在组件的属性中添加指定它.

这是一个有示例工作的plnkr.


小智 5

埃里克马丁内斯的回答很好!请记住,在 Angular4 中不推荐使用 PLATFORM_PIPES。Angular4 中的平台管道是通过 app.modules 配置的:

/**
 * `AppModule`
 */
 @NgModule({
    ...
    providers: [
       ...
       CustomDatePipe
    ]
})
Run Code Online (Sandbox Code Playgroud)