Angular指令上的regex仅返回false

时间:2018-09-27 16:27:02

标签: javascript angular

我想做一个可以允许输入仅输入文本和空格,整数或浮点数的指令。但我只能通过这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个参数中,结果仅为false

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))


        };

    }
}

1 个答案:

答案 0 :(得分:3)

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

完整示例here