【问题标题】:Ionic 3 angular handling currency inputIonic 3 角度处理货币输入
【发布时间】:2018-10-30 00:34:10
【问题描述】:

我有一个 Ionic 3 应用程序,我想将所有货币输入字段格式化为正式方式。如果我输入 10,000,它应该在字段中显示如下:PHP 10,000.00,如果输入数百,它应该显示如下:PHP 100.00

我还想在输入字段时处理 Ionic 中的退格键或清除按钮,以便在 Android 或 iOS 中处理我无法通过 Google 找到的一些解决方案或答案。

我已经找到了一些 jQuery 风格的reference,上面带有jsfiddle

但是当我将代码翻译成 Angular/Ionic 方式时,它并没有解决我的问题。

下面是我的 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
  }

在我的html

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

代码中没有错误。但它不起作用,或者它没有自动将小数位放在数百或数千之间。

有人可以帮我解释一下吗?提前致谢。

【问题讨论】:

标签: javascript angular ionic-framework ionic3 currency


【解决方案1】:

我找到了一个可以解决我的问题的包。我使用ng2-currency-mask 设置您想要的货币格式。但是 Android 和 iOS 上的退格键或清除按钮仍然存在问题,如何处理它。默认情况下它总是返回 229 keyCode

【讨论】:

    【解决方案2】:

    对于 OP,我可能为时已晚,但希望我的解决方案能对未来的访问者有所帮助。我还在medium 上写了一篇博客,以进一步详细说明解决方案。完整的源代码可以在github找到


    解决方案

    通过使用角度数据绑定、货币管道和原生离子输入,可以轻松实现自定义货币输入框。



    首先,我们将创建一个可重用的输入组件:

    number-input.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({
      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();
      }
    
    }
    
    • 组件需要调用者页面的精度初始数量,并输出用户输入/修改的原始数据。
    • 在组件内部,ion-item 封装了字符串字段 formattedAmount 以显示货币格式的值,ion-input 用于捕获用户输入。
    • 通过处理ion-inputionInputkeyup 这两个事件,我们首先使用currency pipe 导出formattedAmount 字段,同时在用户每次击键时分别清理输入框.当然忽略任何非数字键盘输入。这会产生格式漂亮的货币输入框的错觉。
    • 为了帮助将显示文本和输入框幻化为一个实体,触发ion-input 关注离子项目的点击。
    • 使用EventEmitter 将原始用户输入输出到调用父页面。

    然后,我们将在需要用户输入货币格式金额的任何页面中使用它:

    app.page.html

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

    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;
      }
    }
    
    • 通过所需的精度和初始数量。
    • 监听输出事件以捕获原始数据进行计算。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-25
      • 2014-08-01
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-11
      • 2017-11-10
      相关资源
      最近更新 更多