为什么指令不能阻止输入字母符号?

时间:2019-06-01 18:22:10

标签: angular angular5 angular7

指令为:

<div id="mydiv"></div>

我已经测试过,它在此处显示import { Directive, HostListener, Input } from "@angular/core"; @Directive({ selector: "[OnlyAlphabetNumber]" }) export class OnlyAlphabetNumberDirective { constructor() {} @Input() OnlyAlphabetNumber: boolean; @HostListener("keydown", ["$event"]) onKeyDown(event: any) { let e = <KeyboardEvent>event; if (this.OnlyAlphabetNumber) { if (!e.key.match(/^[0-9.]*$/)) { e.preventDefault(); } return; } } }

console.log

所以,我的输入字段是:

if (!e.key.match(/^[0-9.]*$/)) {
     console.log('Wrong');
}

如您所见,它仍然允许输入符号:

enter image description here

0 个答案:

没有答案