0

I'm working on a german local based currency input using ionic(Angular). I want to show something like this

enter image description here

But back end API accepts the value as a floating number.

Ex:- 56.00

what I have currently done is

                    <ion-input 
                        #amount="ngModel"
                        name="AMOUNT"
                        [required]="true"
                        [min]="50"
                        [max]="20000000"
                        (focusout)="rollBackTransformAmount()"
                        (focusIn)="transformAmount()"
                        [ngModel]="formattedAmount"
                        (ngModelChange)="transfer.amount=$event; formattedAmount=$event"
                         placeholder="Amount">
                    </ion-input>

and in ts

  transformAmount(){
    if(!isNaN(this.formattedAmount)){
      this.formattedAmount = this.currencyPipe.transform(this.formattedAmount, 'EUR', 'symbol', '1.2-2', 'de');
    }
  }


  rollBackTransformAmount(){
    // todo
    // this is what I want to implement 
    // get the floating number equivalent for this.formattedValue 
  }

UPDATE - I was able to come up with some thing like follow

 transformAmount(){
    if(!isNaN(this.formattedAmount)){
      this.formattedAmount = this.currencyPipe.transform(this.formattedAmount, 'EUR', 'symbol', '1.0-2', 'de');
    } else {
      this.unFormatCurrencyAmount();
      this.formattedAmount = this.currencyPipe.transform(this.formattedAmount, 'EUR', 'symbol', '1.0-2', 'de');
    }
  }


  rollBackTransformAmount(){
    this.unFormatCurrencyAmount();
    console.log(this.formattedAmount);
  }

  unFormatCurrencyAmount(){
    if(this.formattedAmount){
      // eslint-disable-next-line max-len
      this.formattedAmount = this.formattedAmount.replace(getCurrencySymbol('EUR', 'narrow','de'),'').trim().replaceAll('.','').replace(',','.');
    }
  }

Is there any proper way to achieve this

Kelum Bandara
  • 443
  • 4
  • 9

1 Answers1

2

I strongly suggest you to don't format the variables in your typescript. You should instead only store the plain floating number and only display it in your input component (using currency pipe) as:

<ion-input 
  #amount="ngModel"
  name="AMOUNT"
  type="number"
  [required]="true"
  [min]="50"
  [max]="20000000"
  [ngModel]="formattedAmount | currency:'EUR'"
  (ngModelChange)="transfer.amount=$event;
  placeholder="Amount">
</ion-input>
Fabian Strathaus
  • 3,192
  • 1
  • 4
  • 26
  • If we were to go with this approach problem is formatted value will give error on second time it goes through the currency pipe. Also in typescript I am using currency pipe. – Kelum Bandara Sep 28 '22 at 05:08