[英]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.