我正在制定仅允许使用十进制数字且最多只能包含2位的指令。
但是它没有按预期工作。 Stackblitz如下所示
我面临的错误如下:
答案 0 :(得分:0)
尝试这样的事情:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appDecimalNumber]'
})
export class DecimalNumberDirective {
constructor(private el: ElementRef) { }
@HostListener('keydown', ['$event']) onKeyDown(event: KeyboardEvent) {
let e = <KeyboardEvent>event;
if ([8, 9, 13, 27, 46].indexOf(e.keyCode) !== -1 ||
// Allow: Ctrl+A
(e.keyCode === 65 && (e.ctrlKey || e.metaKey)) ||
// Allow: Ctrl+C
(e.keyCode === 67 && (e.ctrlKey || e.metaKey)) ||
// Allow: Ctrl+V
(e.keyCode === 86 && (e.ctrlKey || e.metaKey)) ||
// Allow: Ctrl+X
(e.keyCode === 88 && (e.ctrlKey || e.metaKey)) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
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();
}
}
@HostListener('keyup', ['$event']) onKeyup(event: KeyboardEvent) {
this.validateFields(event);
}
@HostListener('paste', ['$event']) blockPaste(event: KeyboardEvent) {
this.validateFields(event);
}
//Todo For limit Parse Int
validateFields(event) {
setTimeout(() => {
let numberRegEx = /^[0-9]+$/;
if (!numberRegEx.test(this.el.nativeElement.value)) {
this.el.nativeElement.value = "";
event.preventDefault();
}
}, 100)
}
}