如何在角度 5 中实现货币类型输入?

Har*_*hat 8 input currency-formatting typescript angular

我希望在我的angular 5应用程序中发生以下事情。

我正在输入数值的文本框,一旦该文本框的焦点丢失,我输入的数值应该被格式化为带有 '$' 和 ',',' 的货币。符号。如何实现这一目标?

我想显示我的输入数值,如下图所示。

在此处输入图片说明

The*_*ram 6

在这里,您需要CurrencyPipe对(模糊)事件进行转换。

在您的app.module.ts添加CurrencyPipe提供程序中。

import { CommonModule, CurrencyPipe} from '@angular/common';
@NgModule({
  ... 
  providers: [CurrencyPipe]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

应用组件.html

将事件onblur事件绑定到输入文本框。

<h1>On Focus lost change Format amount</h1>
<input type="text"(blur)="transformAmount($event)" [(ngModel)]="formattedAmount"  />
Run Code Online (Sandbox Code Playgroud)

在您的App.component.ts文件写入方法中transformAmount($event)

应用组件.ts

import { Component,ElementRef } from '@angular/core';
import { CommonModule, CurrencyPipe} from '@angular/common';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
 formattedAmount;
 amount;
   constructor(private currencyPipe : CurrencyPipe) {
  }

   transformAmount(element){
      this.formattedAmount = this.currencyPipe.transform(this.formattedAmount, '$');

      element.target.value = this.formattedAmount;
  }
}
Run Code Online (Sandbox Code Playgroud)

看这个演示

希望以上解决方案对您有所帮助!


Har*_*hat 1

我已经找到办法了..!我在我的 Angular 5 应用程序中安装了一个提供此功能的包。

我就是这样做的。

npm 安装货币格式化程序 --save

.html的代码如下:

<input type="text" [(ngModel)]="taxableValue" (blur)="formatCurrency_TaxableValue($event)">
Run Code Online (Sandbox Code Playgroud)
在文本框模糊处,我调用“formatCurrency_TaxableValue($event)”函数。

.ts文件的代码如下。

formatCurrency_TaxableValue(event)
  {
    var uy = new Intl.NumberFormat('en-US',{style: 'currency', currency:'USD'}).format(event.target.value);
    this.tax = event.target.value;
    this.taxableValue = uy;
  }
Run Code Online (Sandbox Code Playgroud)

这样它对我有用。