3

I understand how to use the DecimalPipe in an Angular 20 HTML template, while importing it in the component code. However, I cannot figure out how to use the DecimalPipe in an Angular service. I keep getting the "No provider" error.

import { DecimalPipe } from '@angular/common';
import { inject, Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class CompareService {

  private readonly decimalPipe = inject(DecimalPipe);
  
    getRows() {
    
        const myValue = 249.19975;
        const cst = decimalPipe .transform(myValue,  '1-0-0');
        
        // additional code here...
    }
  }
}

The error is:

   error.handler.ts:10 ɵNotFound: NG0201: No provider found for `DecimalPipe`. Source: Standalone[Compare..Component]. Path: CompareService -> DecimalPipe.

I've tried to provide it to the parent component - i.e. providers: [DecimalPipe], - but no matter what I do, it keep throwing the error.

Perhaps in the end I cannot use a pipe within a service?

3 Answers 3

3

You need to register it in the providers section of the module (not the parent component) that includes the service.

@NgModule({
  imports: [CommonModule],
  providers: [DecimalPipe] // 👈 register here
})

Or, if standalone (Angular 18+), add the providers inclusion to the service.

bootstrapApplication(AppComponent, {
  providers: [DecimalPipe], // 👈 add here
});
Sign up to request clarification or add additional context in comments.

Comments

2

The general recommendation is to not inject pipes but instead use the underlying function : formatNumber().

Comments

0

You need to register DecimalPipe so inject() can resolve it in app.config.ts:

bootstrapApplication(AppComponent, {
  providers: [
    provideRouter(routes),
    DecimalPipe // provide the pipe
  ],
});

If you only use DecimalPipe in templates:

Just use it in the template:

{{ price | number:'1.0-2' }}

If you must use it in service logic:

  • Global provider (app.config.ts) is best (cleaner & DRY).

  • Use local providers only if you want to strictly limit scope.

2 Comments

It was recommended to me that I move my functions out of the service and into the component itself; basically because the service was not being used by any other components across our app. In this case the DatePipe ended up being easy to use, as a result.
Ok you should register your pipe in component like this: @Component({ selector: 'app-sample', standalone: true, template: ` <p>Formatted Date: {{ formattedDate }}</p> `, providers: [ { provide: DatePipe, useClass: DatePipe } // 👈 provide as class ] })

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.