如何在失去焦点时将输入文本值格式化为角度4上的货币?

时间:2017-08-21 10:05:42

标签: angular angular2-forms

我希望在失去焦点后将输入文本的值格式化为货币。我如何在angular4中实现这一目标?

<input type="text" name="txtamount" [(ngModel)]="amount" />

任何建议都将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:5)

CurrencyPipe上使用(blur)转换。

 <input type="text" name="txtamount" [(ngModel)]="amount" 
        (blur)="transformAmount($event)" [(value)]="formattedAmount"/> 
 <br/>
 <br/>
 <div>
    Formatted Amount on loosing focus: {{ formattedAmount }}
 </div>
 <br/>
 <div>
     Formatted Amount inline with Pipe: {{ amount | currency:'USD'  }}
 </div>

并在您的.ts代码中

transformAmount(element: HtmlElement){
    this.formattedAmount = this.currencyPipe.transform(this.amount, 'USD');
    // Remove or comment this line if you dont want 
    // to show the formatted amount in the textbox.
    element.target.value = this.formattedAmount;
}

您需要从CurrencyPipe导入'@angular/common'并将其添加到应用providers: [ ... ]中。

请参阅此PLUNKER DEMO