I have a service in my application that I need to use Pipe inside it. In the app.module.ts file I didn't import commonModule in import array because I use Standalone approach.
the app.module.ts import array is:
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
IconsModule,
MatDialogModule,
MatSnackBarModule,
HttpClientModule,
],
...
and my service is like this:
@Injectable({
providedIn: 'root',
})
export class ExportService {
constructor(private decimalPipe: DecimalPipe) {}
...
}
I can fix the problem with adding CommonModule in app.module.ts import array like this:
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
**CommonModule,** <-- Added in here
AppRoutingModule,
BrowserAnimationsModule,
IconsModule,
MatDialogModule,
MatSnackBarModule,
HttpClientModule,
],
...
But is there another way to achive this and without importing CommonModule in appModule file?
You can not inject decimalPipe in constructor
You can create a new DecimalPipe
import { DecimalPipe} from '@angular/common';
import { LOCALE_ID, Inject} from '@angular/core';
constructor(@Inject(LOCALE_ID) private locale:string) {}
doIt()
{
const decimalPipe=new DecimalPipe(this.locale)
return decimalPipe.transform(3.141516,'1.0-3')
}
But you can also simply import formatNumber and use it
import { formatNumber } from '@angular/common';
import { LOCALE_ID, Inject} from '@angular/core';
constructor(@Inject(LOCALE_ID) private locale:string) {}
doIt()
{
return formatNumber(3.141516,this.locale,'1.0-2')
}
NOTE: From Angular 8, Angular export the functions formatNumber, formatCurrency, formatPercent and formatDate (from @angular/common) that are the same functions pipes use