i want to format the value of the input text into currency after losing focus. How can i achieve that in angular4?
<input type="text" name="txtamount" [(ngModel)]="amount" />
Any suggestion would be appreciated. Thanks!
Use the CurrencyPipe
transform on (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>
and in your .ts code,
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;
}
You will need to import CurrencyPipe
from '@angular/common'
and add that in App providers: [ ... ]
.
Demo on StackBlitz
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With