11

In my application I need a custom pipe globally, I try to implement it following angular pipe but i see always this error

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

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 
  ],

This pipe works if I import it in all my module and not in the principal app.module, do I need a routin pipe module or something

Alessandro Celeghin
  • 4,039
  • 14
  • 49
  • 95

1 Answers1

23

Pipes (like Components and Directives) don't work globally like services do.

You need to define a pipe in some module. Then you can use it in components defined in that module. Another way is to add the pipe to exports of a module and then import that module in the module where you want to use it.

Define it like this:

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

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

Then import this module where you want to use it and it should work :)

eddyP23
  • 6,420
  • 7
  • 49
  • 87
  • Thanks but is it possible to import my new pipemodule only in appmodule with something like this: `export class SomeUtilModule { static forRoot() { return { ngModule: SomeUtilModule, providers: [], }; } }` – Alessandro Celeghin Jul 14 '17 at 08:46
  • No, I don't think it is, afaik. The idea is that modules have everything in them defined what they need, so they can be easily reused anywhere else without ambiguity. The only exception is services that have non-trivial dependency injection mechanism. – eddyP23 Jul 14 '17 at 08:51
  • 2
    This is really the `SharedModule` which contains exports and declarations of directives and pipes. – Chrillewoodz Jul 14 '17 at 09:43
  • If it's already inserted in a module (ex., like `SharedModule`) pay attention that is must be listed at the `exports` array to be used externally. =] (that was my mistake, `ng g pipe` didn't insert it there, only at `declarations`). – giovannipds Dec 04 '20 at 19:25
  • When starting to use a new custom pipe, I was getting an error "cannot read properties of undefined (reading 'ondestroy')". The key was to export it as shown here and then import into the module where needed. Most of the documentation/examples of pipes mention declaring it. But with multiple modules, that isn't sufficient - the export is also needed. – Paul Evans Nov 18 '22 at 18:51