简体   繁体   English

使用ionic3在输入字段中仅允许数字

[英]Allow only digits in input field using ionic3

I have angular directive to allow only digits in input field. 我有角度指令,仅允许在输入字段中输入数字。 But i try to integrate in ionic3, event.preventDefault() not working. 但是我尝试集成到ionic3中, event.preventDefault()无法正常工作。

can any one suggest the approach to allow only digits. 谁能建议只允许数字的方法。

<ion-input OnlyNumber="true" formControlName="oldpass" type="tel" maxlength="6">

Directive: 指示:

  import { Directive, ElementRef, HostListener, Input } from '@angular/core';

    @Directive({
      selector: '[OnlyNumber]'
    })
    export class OnlyNumber {

      constructor(private el: ElementRef) { }

      @Input() OnlyNumber: boolean;

      @HostListener('keydown', ['$event']) onKeyDown(event) {
        let e = <KeyboardEvent> event;
        if (this.OnlyNumber) {
          if ([46, 8, 9, 27, 13].indexOf(e.keyCode) !== -1) {
              return;
            }
            // Ensure that it is a number and stop the keypress
            if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                e.preventDefault();
                //e.stopPropagation();
                //e.stopImmediatePropagation();
                //return false;
            }
          }
      }
    }

检查一下:

<ion-input formControlName="oldpass" type="text" maxlength="6" pattern="^-?[0-9]*[.]?[0-9]+$">

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

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