javascript - 角度指令上的正则表达式仅返回 false
问题描述
我想做一个指令,可以允许输入只输入文本和空格,或者整数,或者浮点数。但我得到的只是假的,这三种方式
<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();
}
}
}
完整的例子在这里
推荐阅读
- django - 如何在 django 中每次都获取请求用户查询而不点击 DB?
- reactjs - 如何在反应js中将日期放入输入类型日期
- google-cloud-platform - 哪个 gcloud 命令会列出所有计算实例(对于所有 gcp 项目),其网络标签包含特定字符串?
- javascript - 如何询问两次尝试,以便显示有关失败或获胜的通知
- angular - src 属性绑定在 angular6 中不起作用
- python - 在不从“列表”派生的情况下精简 JSON 消息
- google-maps - 仅在一个帐户上无法获得 200 美元的 Google 地图信用额度
- c#-4.0 - 有没有办法用c#逐节阅读word文档
- sap-cloud-sdk - 可以在 docker 中将工件的默认存储库配置为 Nexus 吗?
- python - 将 Python 系统调用限制为 virtualenv 或目录