Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Comma Separated Thousands to Number Inputs in Angular2

Tags:

angular

In Angular 2 how would I add thousands separator for number input controls, so for example

Value in model 1000

When cursor not in input control display separator (e.g. 1,000)

When editing value (i.e. cursor inside control) in input control, it should remove commas to allow the value to be easily edited

Thanks

like image 716
Chris Small Avatar asked Feb 09 '16 18:02

Chris Small


1 Answers

Try this solution, this will solve your problem. Note: Won't work in stack overflow snippet

<input
      type="text"
      name="product_price"
      [(ngModel)]="product_price"
      autocomplete="off"
      (keydown)="numberCheck($event)"
      (keyup)="CommaFormatted($event)"
    />
CommaFormatted(event) {
 // skip for arrow keys
 if(event.which >= 37 && event.which <= 40) return;

 // format number
 if (this.product_price) {
  this.product_price = this.product_price.replace(/\D/g, "")
    .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
 }}

numberCheck (args) {
if (args.key === 'e' || args.key === '+' || args.key === '-') {
  return false;
} else {
  return true;
}}
like image 158
Hardik Shimpi Avatar answered Sep 22 '22 08:09

Hardik Shimpi