简体   繁体   English

Ionic 3 角度处理货币输入

[英]Ionic 3 angular handling currency input

I have an Ionic 3 App where I want to format all currency input field to a formal way.我有一个Ionic 3 应用程序,我想将所有货币输入字段格式化为正式方式。 If I input 10,000 it should show to the field like this: PHP 10,000.00 and if hundreds it should show like this: PHP 100.00 .如果我输入 10,000,它应该像这样在字段中显示: PHP 10,000.00 ,如果输入数百它应该像这样显示: PHP 100.00

I also want to handle the backspace or clear button in Ionic when inputting a field so I can handle that in Android or iOS which I couldn't google to find some solutions or answer.我还想在输入字段时处理Ionic 中的退格键或清除按钮,这样我就可以在Android 或 iOS 中处理它,而我无法在谷歌上找到一些解决方案或答案。

I already have found some reference in jQuery style with a jsfiddle on it.我已经在jQuery样式中找到了一些参考,上面有一个jsfiddle

But when I translate the code into Angular/Ionic way it didn't solve my problem.但是当我将代码翻译成Angular/Ionic 的方式时,它并没有解决我的问题。

Here is my code below in my ts file这是我的ts 文件中的以下代码

handleCurrency(e) {
    console.log(e)
    if (e.keyCode == 8 && this.form.value.amount.length > 0) {
      this.form.value.amount = this.form.value.amount.slice(0, this.form.value.amount.length - 1); //remove last digit
      this.form.value.amount = this.formatNumber(this.form.value.amount);
    }
    else {
      let key = this.getKeyValue(e.keyCode);
      if (key) {
        this.form.value.amount += key; //add actual digit to the input string
        this.form.value.amount = this.formatNumber(this.form.value.amount); //format input string and set the input box value to it
      }
    }
    // return false;
  }

  getKeyValue(keyCode) {
    if (keyCode > 57) { //also check for numpad keys
      keyCode -= 48;
    }
    if (keyCode >= 48 && keyCode <= 57) {
      return String.fromCharCode(keyCode);
    }
  }

  formatNumber(input) {
    if (isNaN(parseFloat(input))) {
      return "0.00"; //if the input is invalid just set the value to 0.00
    }
    let num = parseFloat(input);
    return (num / 100).toFixed(2); //move the decimal up to places return a X.00 format
  }

and in my html在我的html 中

  <ion-input type="number" formControlName="amount" min="0.01" step="0.01" value="0.00" (keypress)="handleCurrency($event)"  placeholder=""></ion-input>

There are no errors in the code.代码中没有错误。 But it doesn't work or it didn't automatically put decimal place between hundreds or thousands.但它不起作用或者它没有自动在数百或数千之间放置小数位。

Can someone shed some light for me?有人可以为我提供一些帮助吗? Thanks in advance.提前致谢。

I found a package that solved my problem.我找到了一个解决我问题的包。 I used ng2-currency-mask to set up your desired currency format.我使用ng2-currency-mask来设置你想要的货币格式。 But still had the problem on backspace or clear button on Android and iOS on how to handle it.但是在Android 和 iOS上的退格键或清除按钮上仍然存在如何处理的问题。 By default it always return 229 keyCode默认情况下它总是返回229 keyCode

I might be too late for OP, but hoping my solution will help future visitors.我对 OP 来说可能为时已晚,但希望我的解决方案能帮助未来的访客。 I have also written a blog on medium to further detail the solution.我还在medium上写了一篇博客来进一步详细说明解决方案。 Full source code can be found on github完整的源代码可以在github上找到


Solution解决方案

By using the angular data binding, currency pipe & native ion-input, a custom currency input box can be easily implemented.通过使用角度数据绑定、货币管道和原生离子输入,可以轻松实现自定义货币输入框。

在此处输入图片说明

First , we will create a reusable input component:首先,我们将创建一个可重用的输入组件:

number-input.component.html数字输入.component.html

<ion-item (click)="openInput()">
    {{ formattedAmount }}
    <ion-input name="dummyFacade" id="dummyFacade" #dummyFacade type="number" inputmode="numeric"
        (keyup)="handleKeyUp($event)" (ionInput)="handleInput($event)"></ion-input>
</ion-item>

number-input.component.js数字输入.component.js

@Component({
  selector: 'app-number-input',
  templateUrl: './number-input.component.html',
  styleUrls: ['./number-input.component.scss'],
  providers: [CurrencyPipe]
})
export class NumberInputComponent implements OnInit {

  private static BACKSPACE_KEY = 'Backspace';
  private static BACKSPACE_INPUT_TYPE = 'deleteContentBackward';

  @ViewChild('dummyFacade', {static: false}) private dummyFacade: IonInput;

  @Input() precision: number;

  @Input() amount: string;

  @Output() amountEntered = new EventEmitter<number>();

  constructor(private currencyPipe: CurrencyPipe) { }

  ngOnInit() {
    if (this.amount && this.amount.trim() !== '') {
      this.amountEntered.emit(+this.amount);
    }
  }

  handleKeyUp(event: KeyboardEvent) {
    // this handles keyboard input for backspace
    if (event.key === NumberInputComponent.BACKSPACE_KEY) {
      this.delDigit();
    }
  }

  handleInput(event: CustomEvent) {
    this.clearInput();
    // check if digit
    if (event.detail.data && !isNaN(event.detail.data)) {
      this.addDigit(event.detail.data);
    } else if (event.detail.inputType === NumberInputComponent.BACKSPACE_INPUT_TYPE) {
      // this handles numpad input for delete/backspace
      this.delDigit();
    }
  }

  private addDigit(key: string) {
    this.amount = this.amount + key;
    this.amountEntered.emit(+this.amount);
  }

  private delDigit() {
    this.amount = this.amount.substring(0, this.amount.length - 1);
    this.amountEntered.emit(+this.amount);
  }

  private clearInput() {
    this.dummyFacade.value = CONSTANTS.EMPTY; // ensures work for mobile devices
    // ensures work for browser
    this.dummyFacade.getInputElement().then((native: HTMLInputElement) => {
      native.value = CONSTANTS.EMPTY;
    });
  }

  get formattedAmount(): string {
    return this.currencyPipe.transform(+this.amount / Math.pow(10, this.precision));
  }

  openInput() {
    this.dummyFacade.setFocus();
  }

}
  • The component expects precision & initial amount from caller page, and outputs user entered/modified raw data.该组件期望来自调用者页面的精度初始数量,并输出用户输入/修改的原始数据。
  • Inside the component, ion-item encapsulates string field formattedAmount to display currency formatted value and ion-input to capture user input.在组件内部, ion-item封装了 string 字段formattedAmount以显示货币格式的值和ion-input以捕获用户输入。
  • By handling both events ionInput & keyup of ion-input , we are first deriving the formattedAmount field using currency pipe and simultaneously clean slating the input box respectively at each keystroke of user.通过处理ion-input ionInputkeyup两个事件,我们首先使用currency pipe派生formattedAmount字段,并同时在用户每次击键时分别清理输入框。 Ofcourse ignoring any non-numeric keyboard input.当然忽略任何非数字键盘输入。 This creates the illusion of pretty formatted currency input box.这会产生格式漂亮的货币输入框的错觉。
  • To help illudes the display text & input box as one entity, trigger the ion-input focus on click of the ion-item.为了帮助将显示文本和输入框显示为一个实体,请在单击离子项时触发ion-input焦点。
  • Using the EventEmitter to ouput the raw user input to the calling parent page.使用EventEmitter将原始用户输入输出到调用父页面。

Then, we will use it across any page where user input for amount in currency format is required:然后,我们将在需要用户以货币格式输入金额的任何页面上使用它:

app.page.html应用程序页面.html

<ion-content>
  <app-number-input [precision]="precision" [amount]="''" (amountEntered)="amountChanged($event)"></app-number-input> 
</ion-content>

app.page.ts app.page.ts

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  amount = 0;

  precision = 2;

  entry;
  constructor() {}

  amountChanged(event: number) {
    this.amount = event;
  }
}
  • Pass the required precision & initial amount.通过所需的精度和初始量。
  • Listen to the output event to capture the raw data for calculation.侦听输出事件以捕获用于计算的原始数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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