Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角度指令上的正则表达式返回值仅为false_Javascript_Angular - Fatal编程技术网

Javascript 角度指令上的正则表达式返回值仅为false

Javascript 角度指令上的正则表达式返回值仅为false,javascript,angular,Javascript,Angular,我想做一个指令,可以允许输入只输入文本和空格,或整数,或浮点。但我得到的只有错误,在这三个方面 <div class="ui-g-10" > <label for="Id">{{'Nome' | doisPontos}}</label><br> <div class="ui-inputgroup"> <input appFi

我想做一个指令,可以允许输入只输入文本和空格,或整数,或浮点。但我得到的只有错误,在这三个方面

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

你非常接近解决方案。要更具角度感,请使用@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();
    }
  }
}

完整示例

如果您记录
过滤器
this.el.nativeElement.value的值
输出是什么?过滤器值:/[a-zA-Z]/el本机值:现在我明白了,过滤器是空的或空的,为什么?它的工作,非常感谢您,我将进一步研究hotlistener
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();
    }
  }
}