Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No Provider for CustomPipe - angular 4

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.

like image 211
mperle Avatar asked Sep 19 '17 12:09

mperle


2 Answers

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 { } 
like image 187
Stefan Svrkota Avatar answered Sep 19 '22 22:09

Stefan Svrkota


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.

like image 23
Faruq Avatar answered Sep 21 '22 22:09

Faruq