简体   繁体   English

如何使用指令仅允许在输入类型“ tel”中输入数字(0-9)-Ionic 3 Angular 5

[英]How to only allow digits(0-9) to be entered in input type 'tel' using directive - Ionic 3 Angular 5

I'm trying to make a custom directive which will allow only digits to be entered in input type= 'tel' . 我正在尝试制定一个自定义指令,该指令仅允许在输入type ='tel'输入数字。 Well in Ionic 1 (angular1) I used directive as follows which worked efficiently 在Ionic 1(angular1)中,我使用了如下指令,该指令有效地工作

.directive('onlyDigits', function() {
  return {
      restrict: 'A',
      require: '?ngModel',
      link: function(scope, element, attrs, modelCtrl) {
          modelCtrl.$parsers.push(function(inputValue) {
            if (inputValue == undefined) return '';
            var transformedInput = inputValue.replace(/[^0-9]/g, '');
            if (transformedInput !== inputValue) {
              modelCtrl.$setViewValue(transformedInput);
              modelCtrl.$render();
            }
            return transformedInput;
          });
      }
  };
})

Now in Ionic 3(angular5), I'm trying to recreate the same directive with following code. 现在在Ionic 3(angular5)中,我尝试使用以下代码重新创建相同的指令。

import { Directive, ElementRef, Output, Renderer, HostListener, EventEmitter } from '@angular/core';
@Directive({ selector: '[onlyDigits]' })
export class DigitsDirective {
    constructor(public elementRef: ElementRef, public renderer: Renderer) {}

    @Output() onlyDigits = new EventEmitter();

    @HostListener("keyup", ["$event.target.value"])
    onKeyup(value) {
        if (value == undefined) return '';
        var transformedInput = value.replace(/[^0-9]/g, '');
        if (transformedInput !== value) {
          this.onlyDigits.emit(transformedInput);
        }
    }
} 

This kinda works, but there is one problem. 这有点用,但是有一个问题。 Because of keyup event it first adds the non-digit letter to input type then removes it. 由于发生键事件,它首先将非数字字母添加到输入类型,然后将其删除。 In above ionic 1 directive if we press non-digit value, it doesn't let that value get inside the input type but in Ionic 3 first, the value is added in input type than it is removed which I don't want! 在上面的ionic 1指令中,如果我们按非数字值,则不会让该值进入输入类型,但首先在Ionic 3中,该值会在输入类型中添加,而不是我不希望删除的值! how to achieve this feat? 如何实现这一壮举?

Created a custom directive which will allow only digits. 创建了一个仅允许数字的自定义指令。 (For Ionic 3) This solution worked for me. (适用于Ionic 3)此解决方案对我有用。 Please try below code. 请尝试以下代码。

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

     @Directive({
     selector: '[onlyDigits]' // Attribute selector
     })
     export class OnlyDigitsDirective {

     constructor(private _el: ElementRef) {
     console.log('Hello OnlyDigitsDirective Directive');
     }
     @Output() onlyDigits = new EventEmitter();

     @HostListener('keydown', ['$event']) onKeyDown(event) {
     let e = <KeyboardEvent>event;

     if (e.key == "0" || e.key == "1" || e.key == "2" || e.key == "3" || 
         e.key == "4" || e.key == "5" || e.key == "6" || e.key == "7" || 
         e.key == "8" || e.key == "9" || e.key == "Backspace") {
         // Do Nothing
         console.log("e.key: " + e.key);
         } else {
         // does not allow 
           e.preventDefault();
          }

        }


      }

I don't know if you want another way but I solved this with jquery. 我不知道你是否想要另一种方法,但是我用jquery解决了这个问题。

npm install -g typings typings install dt~jquery --global --save npm install -g键入键入install dt〜jquery --global --save

jquery solution: jQuery的解决方案:

 $('#YOUR_ID').on('textInput', e => {    
    var keyCode = e.originalEvent.data.charCodeAt(0);                       
    if(!(keyCode>64 && keyCode<91) && !(keyCode>96 && keyCode<123) && !(keyCode>127 && keyCode<166) ){
      e.preventDefault();
    }
  });

Oh no, nonono @berk-akkerman, don't use jquery with Angular! 哦,不,nonono @ berk-akkerman,不要将jQuery与Angular一起使用! DO NOT DO THAT! 不要那样做! I strictly forbid you! 我严格禁止你!

Here's one simple way using NgModel, but bear in mind that validators would probably give you a better UX, ie. 这是使用NgModel的一种简单方法,但是请记住,验证器可能会为您提供更好的UX,即。 let user input whatever, but show an error msg if the field is invalid, and don't let them submit. 让用户输入任何内容,但如果该字段无效,则显示错误消息,并且不要让他们提交。

Component 零件

data = {numberValue: 0};
ensureNumber(val:any) {
    return (''+val).replace(/[^0-9]/g, '');
}

Template 模板

<input type="number" [ngModel]="data.numberValue"
 (ngModelChange)="data.numberValue=ensureNumber($event)"/>

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

相关问题 使用Angular 2 / Ionic 2将输入类型=“tel”更改为密码字段 - Changing input type=“tel” to password field using Angular 2/Ionic 2 使用ionic3在输入字段中仅允许数字 - Allow only digits in input field using ionic3 Angular:如何使用指令在文本框中仅允许 integer - Angular: How to allow only integer in the textbox using Directive Angular2 - 只允许在输入中输入字母字符 - Angular2 - Only Allow Alpha Characters TO Be Entered In An Input Angular 2/4 需要一个 Typescript 正则表达式来只允许将数字输入到输入文本框中 - Angular 2/4 need a Typescript regex to only allow numbers to be entered into input textbox 如何在角度2中创建仅允许文本的指令 - How to create directive in angular 2 that to allow text only 如何在 IONIC 3 中为国际电话输入创建 IONIC 组件 - How to create IONIC component for intl-tel-input in IONIC 3 在Ionic 2 Angular 2中输入数字位数时打开模态怎么办? - Open a modal when input a total number of digits in Ionic 2 Angular 2 how to? 如何使用TypeScript只允许html输入类型文本中的数字? - How to allow only numbers in html input type text using TypeScript? Angular 指令 - 只有数字和 2 位小数,用逗号分隔 - Angular directive - Only digits and 2 decimals with comma separated
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM