找不到 Angular 自定义管道

标签 angular angular2-custom-pipes

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

Template parse errors: The pipe 'formatdate' could not be found

格式日期.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 中,这个管道就可以工作,我需要一个常规管道模块还是什么

最佳答案

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

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

这样定义:

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

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

然后在你想使用它的地方导入这个模块,它应该可以工作:)

关于找不到 Angular 自定义管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45098278/

相关文章:

angular - ngselect 中未显示占位符

angular - angular 中的多个应用程序组件

Angular - 将小数限制为两位而不四舍五入

Angular6 尝试使用 DecimalPipe 到自定义管道时出现错误

Angular 2 - 如何在自定义管道中使用内置管道

angular - 自定义管道实例位于何处?组件代码如何访问在其 HTML 中使用的自定义管道实例?

angular - 如何禁用/抑制 TypeScript 库中的错误?

angular - 在 Angular 2 中创建新组件时出现此错误。!