简体   繁体   中英

Angular - Automatically add Commas to a Number in a Inputbox?

I want to Automatically add Commas to a Number in a Input Box in Angular.

app.component.html

 <div class="buttons">
   <div *ngFor="let product of products" class="row p-0 m-1">
      <button class="btn btn-lg btn-outline-secondary col p-1 m-1" type="button" (click)="clickData(product.button1)">{{product.button1}}</button>
      <button class="btn btn-lg btn-outline-secondary col p-1 m-1" type="button" (click)="clickData(product.button2)">{{product.button2}}</button>
      <button class="btn btn-lg btn-outline-secondary col p-1 m-1" type="button" (click)="clickData(product.button3)">{{product.button3}}</button>
      <button [ngClass]="product.button4 === '=' ? 'btn-blue btn-lg btn-outline-secondary col p-1 m-1' : 'btn btn-lg btn-outline-secondary col p-1 m-1'" type="button" (click)="clickData(product.button4)">{{product.button4}}</button>
    </div>
</div>

app.component.ts

 clickData(num: string){

if (num=="0") {
  if (this.input !="" ) {

    const lastNum=this.getLastOperand()
    if (lastNum.lastIndexOf("0") >= 0) return;
  }
}

if (num=="0") {
  if (this.input=="" ) {
    return;
  }
  const PrevKey = this.input[this.input.length - 1];
  if (PrevKey === '/' || PrevKey === '*' || PrevKey === '-' || PrevKey === '+')  {
      return;
  }
}

this.input = this.input + num

console.warn("op",this.input)

this.closebutton.nativeElement.click();

}

The above code is Html file and .ts file. I want when I click on button which is 00 button it will automatically add comma. Thanks in advance.

so as you said want to add the commas to number below is the solutions

in .ts file

InputOnchange(value) {
    const replace = value.replace(/,/g, '');
    const number = parseInt(replace);
    this.value = number;
   
  }

processMyValue(amount) {
    if (isNaN(amount) || amount === null || amount === '') {
      return amount;
    } else {
      const replace = amount.replace(/,/g, '');
      const number = parseInt(replace);
    }    
  }

in .html file

     <mat-form-field >
<mat-label>Amount</mat-label>
                                    <input (input)="InputOnchange($event.target.value)" autocomplete="off"
                                        matInput placeholder="Amount "
                                        formControlName="amount_Amount" required
                                        (wheel)="$event.preventDefault()"
                                        (focusout)="processMyValue($event.target.value)"
                                        />
                                </mat-form-field>
    
 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM