0

I want to add Commas to Input box while typing into in. how can we do that ? Currently I am trying to do it via onkeyup function converting that value to commas and then binding it to input but its not giving proper output.

Code I am Using :

<input type="text" (keyup)="getValueWithCommas($event)" matInput placeholder="Budget" formControlName="Budget" [value]="a">

getValueWithCommas(event){
    this.a = event.target.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  }

but this is not working properly it placing commas in wrong places. But If I am binding this value to some span below input then its working correctly why is it so ?

Amit
  • 71
  • 7

1 Answers1

0

Use Angular Directive to formate the input value.

Here is what I did.

step 1: create directive using angular-CLI

ng g d comma

step 2: Html part

<input type="text" id="input" class="form-control" appComma>

step 3: update comma.directive.ts with following code.

import { Directive, HostListener, ElementRef  } from '@angular/core';

@Directive({
  selector: '[appComma]'
})
export class CommaDirective {


  constructor(private el: ElementRef) { }
  @HostListener('blur') onBlur() {
    let value :number= this.el.nativeElement.value * 1; // multiply by 1 to convert to number
    this.el.nativeElement.value = value.toLocaleString()
  }


}
Muhammad Shahab
  • 197
  • 1
  • 8