Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format input text value to currency on angular 4 on lost focus?

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!

like image 838
Juan Avatar asked Aug 21 '17 10:08

Juan


1 Answers

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

like image 172
Faisal Avatar answered Oct 17 '22 13:10

Faisal