NullInjectorError: No provider for DecimalPipe

12,325

Solution 1

You need to provide the DecimalPipe in the Module that provides your Service

for example, if your service is "providedIn: 'root'" then you should provide the DecimalPipe in your AppModule like that:

import {DecimalPipe} from '@angular/common';
@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [ ],
  providers: [DecimalPipe],
  exports: [],
  bootstrap: [AppComponent]
})
export class AppModule {
}

Solution 2

If you want to create a shared NgModule that you import instead of CommonModule in all of your feature modules. You would do something like this:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

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

Then, in all of your feature modules, you would forgo importing CommonModule and instead import your SharedModule. This should give your custom code access to all of the Pipes and Components within the CommonModule.

You should not include Angular's built-in Pipes nor Components in the declarations of your NgModules as they are already declared in Angular's NgModules.

If all you are doing is trying to use the DecimalPipe in a component, importing the CommonModule in the NgModule where you provide your service should get you access to the pipe.

Share:
12,325
Ravi
Author by

Ravi

Eat.Code.Sleep

Updated on June 23, 2022

Comments

  • Ravi
    Ravi almost 2 years

    I have implemented lazy loading in my application. One of my services needs to include DecimalPipe.

    service --> shared module --> App module

    This is my structure. I've already included "CommonModule" in app.module.ts and My service also needs Decimal Pipe.

    1. Including "Decimal Pipe" in my shared module gives the below error:

    Type DecimalPipe is part of the declarations of 2 modules: CommonModule and SharedModule! Please consider moving DecimalPipe to a higher module that imports CommonModule and SharedModule. You can also create a new NgModule that exports and includes DecimalPipe then import that NgModule in CommonModule and SharedModule.

    So Since it is already part of Commons Module, why doesn't it take Decimal pipe from Commons Module. ? If It is not declared, below error is shown

    NullInjectorError: No provider for DecimalPipe!

    Please let me know how to handle this error. Thanks in advance!

  • Ben Taliadoros
    Ben Taliadoros almost 4 years
    This doesn't work, I have a shared modules importing and exporting CommonModule into all modules but if iI want to use the decimalPipe in a component I still have to provide it at the component level
  • Ali Celebi
    Ali Celebi over 2 years
    This approach helped me resolve this issue.