首页 > 解决方案 > 角度指令上的正则表达式仅返回 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))


        };

    }
}

标签: javascriptangular

解决方案


您非常接近解决方案。更有棱角——利用@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();
    }
  }
}

完整的例子在这里


推荐阅读