No Provider for CustomPipe - angular 4

AngularAngular ModuleAngular Pipe

Angular Problem Overview


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.

Angular Solutions


Solution 1 - Angular

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 { }

Solution 2 - Angular

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.

Solution 3 - Angular

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 {
      ...
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmperleView Question on Stackoverflow
Solution 1 - AngularStefan SvrkotaView Answer on Stackoverflow
Solution 2 - AngularFaruqView Answer on Stackoverflow
Solution 3 - AngularJosé Antonio PostigoView Answer on Stackoverflow