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

Jua*_*uan 3 angular2-forms angular

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

<input type="text" name="txtamount" [(ngModel)]="amount" />
Run Code Online (Sandbox Code Playgroud)

任何建议将不胜感激.谢谢!

Fai*_*sal 6

使用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>
Run Code Online (Sandbox Code Playgroud)

在你的.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;
}
Run Code Online (Sandbox Code Playgroud)

您需要CurrencyPipe'@angular/common'App 导入并在App中添加providers: [ ... ].


看这个PLUNKER DEMO

  • 值得一提的是这会改变实际的输入值。这可能没问题,但有时您只想格式化视图值。 (4认同)