找不到角度自定义管道

时间:2017-07-14 08:29:04

标签: angular angular2-custom-pipes

在我的应用程序中,我需要全局自定义管道,我尝试在angular pipe之后实现它  但我总是看到这个错误

  

模板解析错误:管道'格式化日期'无法找到

formatdate.pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'formatdate'
})

export class FormatdatePipe implements PipeTransform {

  transform(dateJson: any, args?: any): any {
.
 //code...
.
      return dateJson;
    }
  }
}

app.module

import { FormatdatePipe } from './shared/pipes/formatdate.pipe';
@NgModule({
  declarations: [
    AppComponent, FormatdatePipe 
  ],

如果我在我的所有模块中导入它而不在主app.module中导入此管道,我是否需要一个例程管道模块或其他东西

1 个答案:

答案 0 :(得分:13)

管道(如组件和指令)不像服务那样​​在全球范围内工作。

您需要在某个模块中定义管道。然后,您可以在该模块中定义的组件中使用它。另一种方法是将管道添加到模块的导出,然后将该模块导入到要使用它的模块中。

像这样定义:

import { FormatdatePipe } from './shared/pipes/formatdate.pipe';

@NgModule({
  declarations: [
    FormatdatePipe 
  ],
  exports: [
    FormatdatePipe
  ]
})   
export class SomeUtilModule {}

然后将此模块导入您要使用它的位置,它应该可以工作:)

相关问题