Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.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
Angular 如何防止输入中出现退格符号?_Angular - Fatal编程技术网

Angular 如何防止输入中出现退格符号?

Angular 如何防止输入中出现退格符号?,angular,Angular,我在Angular 2中执行了此指令,以防止输入字段中的退格符号小于3: import {Directive, ElementRef, HostListener, Input} from '@angular/core'; @Directive({ selector: '[limitTo]' }) export class RestrictInputDirective { @Input() limitTo: number; constructor(private el: Elem

我在Angular 2中执行了此指令,以防止输入字段中的退格符号小于3:

import {Directive, ElementRef, HostListener, Input} from '@angular/core';

@Directive({
  selector: '[limitTo]'
})
export class RestrictInputDirective {

  @Input() limitTo: number;

  constructor(private el: ElementRef) {
  }

  @HostListener('keydown', ['$event'])
  onKeyDown(evt: KeyboardEvent) {
    let a = (evt.target as HTMLInputElement).value.length;
    if (a <= this.limitTo) {
      evt.preventDefault();
    }
  }
}
import{Directive,ElementRef,HostListener,Input}来自“@angular/core”;
@指示({
选择器:“[Limito]”
})
导出类限制输入指令{
@Input()limito:数字;
构造函数(专用el:ElementRef){
}
@HostListener('keydown',['$event']))
onKeyDown(evt:KeyboardEvent){
设a=(evt.target作为HTMLInputElement).value.length;

如果(a您可以使用keyDown.backspace伪事件来防止退格

@Directive({
  selector: '[appLimitTo]'
})
export class LimitToDirective {
  @Input('appLimitTo') limitTo: number=5;
  constructor(private el: ElementRef) { }
  @HostListener('keydown.backspace', ['$event'])
  onKeyDown(evt: KeyboardEvent) {
   console.log(evt.target.value);
    let a = (evt.target as HTMLInputElement).value.length; 
     if (a <= this.limitTo) {
      evt.preventDefault();
    }

  }
}
@指令({
选择器:“[Applimito]”
})
导出类LimitToDirective{
@输入('Applimito')限制:数字=5;
构造函数(私有el:ElementRef){}
@HostListener('keydown.backspace',['$event']))
onKeyDown(evt:KeyboardEvent){
日志(evt.target.value);
设a=(evt.target作为HTMLInputElement).value.length;

如果(这一行有问题:``console.log(evt.target.value);``将代码更改为console.log(evt.target['value'));如下所示
@Directive({
  selector: '[appLimitTo]'
})
export class LimitToDirective {
  @Input('appLimitTo') limitTo: number=5;
  constructor(private el: ElementRef) { }
  @HostListener('keydown.backspace', ['$event'])
  onKeyDown(evt: KeyboardEvent) {
   console.log(evt.target.value);
    let a = (evt.target as HTMLInputElement).value.length; 
     if (a <= this.limitTo) {
      evt.preventDefault();
    }

  }
}