我想在失去焦点后将输入文本的值格式化为货币。我怎样才能在 angular4 中实现这一点?
<input type="text" name="txtamount" [(ngModel)]="amount" />
如有任何建议,我们将不胜感激。谢谢!
最佳答案
在 (blur)
上使用 CurrencyPipe
转换。
<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;
}
您需要从 '@angular/common'
导入 CurrencyPipe
并将其添加到 App providers: [ ... ]
中。
演示 StackBlitz
关于angular - 如何在失去焦点时将输入文本值格式化为 Angular 4 上的货币?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45794381/