角度指令上的正则表达式只返回 false



我想做一个指令,可以允许输入仅输入文本和空格,整数或浮点数。 但我只得到假的,在这 3 种方式

<div class="ui-g-10"  >
<label for="Id">{{'Nome' | doisPontos}}</label><br>
<div class="ui-inputgroup">
<input appFiltrarTipo type="text" formControlName="Nome" style="text-align: left; width: 450px;" id="Nome" appUppercase  [(ngModel)]="secaoForm.value.Nome" [value]="secaoForm.value.Nome" pInputText >
</div>
</div>

我传递了我想要的参数 preventDefault((,但在这 3 个参数中,结果只是假

import {Directive, ElementRef, Input} from '@angular/core'
let input = Input
@Directive({
selector: '[appFiltrarTipo]'
})
export class FiltrarTipoDirective {
private readonly REGEX = {
text: '[a-zA-Z ]',
integer: '[0-9]',
float: '[0-9.]'
}
private readonly specialKeys = [ 'Backspace', 'Tab', 'End', 'Home', '-' ];
@input() type: string;
constructor(public el: ElementRef) {
this.el.nativeElement.onkeypress = (evt) => {
if(this.specialKeys.indexOf(evt.key) !== -1) return;
let filter = new RegExp(this.REGEX[this.type])
if(!filter.test(this.el.nativeElement.value)){
event.preventDefault();
}
console.log(filter.test(this.el.nativeElement.value))

};
}
}

你非常接近解决方案。更有棱角 - 杠杆@HostListener。正如其中一条评论所建议的那样 - 您正在检查事件发生的元素(输入(的值。相反,您应该检查您按下的键值

import { Directive, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appFiltrarTipo]'
})
export class AppFiltrarTipo {
@Input() type: string;
private readonly REGEX = {
text: '[a-zA-Z ]',
integer: '[0-9]',
float: '[0-9.]'
}
private readonly specialKeys = ['Backspace', 'Tab', 'End', 'Home', '-'];
@HostListener('keypress', ['$event'])
onKeyPress(event: KeyboardEvent) {
if (this.specialKeys.indexOf(event.key) !== -1) return;
const filter = new RegExp(this.REGEX[this.type])
if (!filter.test(event.key)) {
event.preventDefault();
}
}
}

完整示例在这里

最新更新