54

I've a custom decimal format pipe that uses angular Decimal pipe inturn. This pipe is a part of the shared module. I'm use this in feature module and getting no provider error when running the application.

Please ignore if there are any typo.

./src/pipes/custom.pipe.ts

import { DecimalPipe } from '@angular/common';
..
@Pipe({
    name: 'customDecimalPipe'
})
...
export class CustomPipe {
constructor(public decimalPipe: DecimalPipe) {}
transform(value: any, format: any) {
    ...
}

./modules/shared.module.ts

import  { CustomPipe } from '../pipes/custom.pipe';

...

@NgModule({
  imports:      [ .. ],
  declarations: [ CustomPipe ],
  exports:    [ CustomPipe ]
})
export class SharedModule { }

I inject the custom pipe in one of the components and call transform method to get the transformed values. The shared module is imported in he feature module.

mperle
  • 2,514
  • 7
  • 12
  • 31
  • Possible duplicate of [Angular 2/4 use pipes in services and components](https://stackoverflow.com/questions/35144821/angular-2-4-use-pipes-in-services-and-components) – alexKhymenko Sep 19 '17 at 12:11

3 Answers3

116

If you want to use pipe's transform() method in component, you also need to add CustomPipe to module's providers:

import  { CustomPipe } from '../pipes/custom.pipe';

...

@NgModule({
  imports:      [ .. ],
  declarations: [ CustomPipe ],
  exports:    [ CustomPipe ],
  providers:    [ CustomPipe ]
})
export class SharedModule { }
Stefan Svrkota
  • 40,477
  • 8
  • 90
  • 83
12

Apart from adding the CustomPipe to the module's provider list, an alternative is to add to the component's providers. This can be helpful if your custom pipe is used in only a few components.

import  { CustomPipe } from '../pipes/custom.pipe';
...
@Component({
    templateUrl: './some.component.html',
    ...
    providers: [CustomPipe]
})
export class SomeComponent{
    ...
}

Hope this helps.

Faruq
  • 1,024
  • 8
  • 23
  • 2
    This makes much more sense than the accepted answer (cannot believe upvotes are 10x less)! A pipe designed for a specific component **should not be available globally**. Appreciated the logic Faruq. – CPHPython Aug 10 '20 at 19:28
12

You could also make the pipe Injectable (the same way it is done with the services you create using the cli):

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

    @Pipe({
      name: 'customDecimalPipe'
    })
    @Injectable({
      providedIn: 'root'
    })
    export class CustomPipe extends PipeTransform {
      ...
    }
José Antonio Postigo
  • 1,812
  • 14
  • 16