How to tell angular (2) currency to display as is if the value is a string that is not int or float

In the currency channel, if we pass a string, it should do nothing but return a string, and if we pass an int or float, it should format the value and show the formatted number.

This happened in angularJs but did not happen in angular (2)

How to avoid a currency pipe in case of its string and currency formatting, if its decimal value. I expect something like below.

Example

if the value of the money in the lower code is "included / no / postpaid",   <div>Money: {{money | currency:'USD':true:'1.2-2'}}</div>should be displayed   included/none/postpaid

if the value of money in the lower code is equal to '11 .99 ', <div>Money: {{money | currency:'USD':true:'1.2-2'}}</div>  should display the symbol $11.99- $.

Error I am getting:  caused by: Invalid argument 'Included' for pipe 'CurrencyPipe'

I think this happened by default in angularjs, but in angular2 it doesn't happen on defalut.

+4
source share
2 answers

The manual explicitly states that it accepts a numeric expression and nothing else:

number_expression | Currency [: CurrencyCode [: symbolDisplay [: digitInfo]]]

The pipe is very simple and can be expanded and used instead CurrencyPipeto match expected behavior:

const _NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/;

@Pipe({name: 'currency'})
export class LooseCurrencyPipe extends CurrencyPipe {
  transform(value: any, currencyCode: string, symbolDisplay: boolean, digits: string): string {
    if (typeof value === 'number' || _NUMBER_FORMAT_REGEXP.test(value)) {
      return super.transform(value, currencyCode, symbolDisplay, digits);
    } else {
      return value;
    }
  }
}

To create a new channel with a different name, it CurrencyPipecan be entered into a user channel:

@Pipe({name: 'looseCurrency'})
export class LooseCurrencyPipe implements PipeTransform {
  constructor(private _currencyPipe: CurrencyPipe) {}

  transform(value: any, currencyCode: string, symbolDisplay: boolean, digits: string): string {
    if (typeof value === 'number' || _NUMBER_FORMAT_REGEXP.test(value)) {
      return this._currencyPipe.transform(value, currencyCode, symbolDisplay, digits);
    } else {
      return value;
    }
  }
}

To CurrencyPipebe introduced via DI, it must be added to the module providers:

declarations: [LooseCurrencyPipe, ...],
providers: [CurrencyPipe, ...],
+5
source

a ? b : c, b, a , c .

, true, .

isNumber(e) {return typeof e === 'number'}

, , .

<div>
    {{ isNumber(money) ? (money|currency:'USD':true:'1.2-2') : money }}  
</div>

+8

Source: https://habr.com/ru/post/1658381/


All Articles