Angular6 Getting error while trying to using DecimalPipe to a custom pipe

4.9k Views Asked by At

I am trying to inject DecimalPipe to my custom pipe as described in this answer.

here is the code:

@Pipe({name: 'irc'})
export class IRCurrencyPipe implements PipeTransform {

  constructor(private decimalPipe: DecimalPipe) {}

  transform(value: string | number, type: string = 'rial') {
    value = Number(value);
   if (isNaN(value)) { throw new Error(`${value} is not a acceptable number`); }
    return this.decimalPipe.transform(value, '1.0-0') + ' ریال';
  }
}

But I get TypeError: Cannot read property 'transform' of undefined error when running tests from this code.

I also tried extending the DecimalPipe as suggested in this answer :

@Pipe({name: 'irc'})
export class IRCurrencyPipe extends DecimalPipe implements PipeTransform {


  transform(value: string | number, type: string = 'rial') {
    value = Number(value);
    if (isNaN(value)) { throw new Error(`${value} is not a acceptable number`); }
    return super.transform(value, '1.0-0') + ' ریال';
  }
}

But I get: Error: InvalidPipeArgument: 'Cannot read property 'toLowerCase' of undefined' for pipe 'DecimalPipe' in this case. Is there a working solution to using one of the built-in pipes in angular to a custom pipe?

3

There are 3 best solutions below

2
Sachin Jagtap On

I tried and I am getting the result. See the code

import { DecimalPipe } from '@angular/common';
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'currency'})
export class CurrencyPipe extends DecimalPipe implements PipeTransform {
    transform(value: string | number, type: string = 'rial') {
        value = Number(value);
        if (isNaN(value)) { throw new Error(`${value} is not a acceptable number`); }
        return super.transform(value, '1.0-0') + ' ریال';
    }
}

1
Dmitry Efimenko On

This happens when you don't have LOCALE_ID set. You can set it like this:

import { LOCALE_ID, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from '../src/app/app.component';

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ AppComponent ],
  providers: [ { provide: LOCALE_ID, useValue: 'fr' } ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

See full docs here

0
daniel-sc On

In your unit test you'd need to register any non-default locale (additionally to providing LOCALE_ID):

import localeFr from '@angular/common/locales/fr';

beforeEach(() => {
  registerLocaleData(localeFr);
});

See https://angular.io/guide/i18n#i18n-pipes