Add Comma Separated Thousands to Number Inputs in Angular2

As Mark commented above you want to use a pipe. You can create a Pipe using the following syntax, then simply add the pipe to your component using the pipes property on the component decorator.

@Pipe({name: 'commaSeparatedNumber'})
export class CommaSeparatedNumberPipe implements PipeTransform {
  transform(value:number, args:string[]) : any {
    return // Convert number to comma separated number string
  }
}

@Component({
  ...
  template: `
    <div *ngIf="!editing">{{number | commaSeparatedNumber}}</div>
    <input type="number" [(ngModel)]="number" />
  `,
  pipes: [CommaSeparatedNumberPipe]
})
class MyComponent{
  public editing: boolean;
  public number: number;
  ...
}

UPDATE

In that case I would recommend listening to the focus and blur events on the input

@Component({
  ...
  template: `<input type="text" [(ngModel)]="number" 
              (focus)="removeCommas()" (blur)="addCommas()" />`
})
class MyComponent{
  number: string;

  removeCommas(){
    this.number = this.number.replace(',', '');
  }

  addCommas(){
    this.number = // Convert number to comma separated number string
  }
}

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;
}}

Tags:

Angular