0

数値が文字列形式で、文字列に小数点がない場合、Angular 通貨パイプは文字列/整数を通貨形式に変換しません。

金額が 12 で、$12.00 を表示したい場合、「12」が渡されると表示されませんが、12.00 が渡されると正しく機能します。

//Code

import {Pipe, PipeTransform} from "@angular/core";
import {CurrencyPipe} from "@angular/common";
const _NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/;

@Pipe({name: 'myCurrency'})
export class MyCurrencyPipe 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;
    }
  }
}


@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <div>{{priceNoDecimal}}</div> {{priceNoDecimal | myCurrency}}
      <div>{{priceWithDecimal}}</div> {{priceWithDecimal | myCurrency}}      
    </div>
  `,
})
export class App {
  name:string;
  priceWithDecimal: string;
  priceNoDecimal: string;
  constructor() {
    this.name = 'Angular2',
    this.priceNoDecimal = "12"
    this.priceWithDecimal = "12.00"
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App , MyCurrencyPipe],
  providers: [CurrencyPipe],
  bootstrap: [ App ]
})
export class AppModule {}


//output

Hello Angular2

12
12
12.00
USD12.00

プランカー

4

2 に答える 2

1

質問は文脈がないと不明確かもしれません。前の回答のパイプは、文字列内の数値を検出するために元の数値パイプで使用される正規表現です。

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

元の currency パイプの入力条件を厳密に模倣するために、パイプを次のように変更できます。

function isNumeric(value: any): boolean {
  return !isNaN(value - parseFloat(value));
}

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

  transform(value: any, currencyCode: string, symbolDisplay: boolean, digits: string): string {
    value = typeof value === 'string' && isNumeric(value) ? +value : value;

    if (typeof value === 'number') {
      return this._currencyPipe.transform(value, currencyCode, symbolDisplay, digits);
    } else {
      return value;
    }
  }
}

フレームワークの internalsisNumericから抽出されたヘルパー関数はどこにありますか。このアプローチでうまくいくはずです。

于 2016-10-21T22:01:38.437 に答える