如何以 angular 反应形式使用指令

How to use directive in angular reactive form

我正在尝试在我的 HTML 中添加一个指令,这样我就可以只允许用户输入数字。

这是我的指令

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

@Directive({
  selector: '[OnlyNumber]'
})

export class OnlyNumber {

  regexStr = '^[0-9]*$';
  constructor(private el: ElementRef) { }

  @Input() OnlyNumber: boolean;

  @HostListener('keydown', ['$event']) onKeyDown(event: any) {
    let e = <KeyboardEvent>event;
    if (this.OnlyNumber) {
      if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
        // Allow: Ctrl+A
        (e.keyCode == 65 && e.ctrlKey === true) ||
        // Allow: Ctrl+C
        (e.keyCode == 67 && e.ctrlKey === true) ||
        // Allow: Ctrl+V
        (e.keyCode == 86 && e.ctrlKey === true) ||
        // Allow: Ctrl+X
        (e.keyCode == 88 && e.ctrlKey === true) ||
        // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
        // let it happen, don't do anything
        return;
      }
      let ch = String.fromCharCode(e.keyCode);
      let regEx = new RegExp(this.regexStr);
      if (regEx.test(ch))
        return;
      else
        e.preventDefault();
    }
  }
}

我在HTML中使用过这个指令。

<div class="form-group">
                  <h6>Estimated Hours</h6>
                  <input type="text" class="form-control rounded-0" placeholder="Estimated Hours"  formControlName="EstimatedHours" OnlyNumber>
                </div>

我在声明下的 app.module.ts 中添加了指令。我在这里遗漏了什么吗,因为我可以输入任何字母。

使用Validator.pattern

TS

let reg = /^\d+$/;
   this.Form=new FormGroup({
     number: new FormControl('',[Validators.pattern(reg)])
   })

HTML

<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8 col-md-offset-2 col-sm-offset-1">
      <form [formGroup]="Form" >
         <input formControlName="number">
         <button (click)="onSubmit()">Submit</button>
        </form>
      </div>  
  </div>
</div>

并且如果你想在 hostlistner 中获取值你不需要使用输入 属性 绑定只需使用 $event 对象来获取值

@HostListener('keydown',['$event']) onChange($event){  
  console.log($event.target.value) 
}

您可以试试这个解决方案

我已经在 stackblitz

上创建了一个演示

html code

<div class="form-group">
    <h6>Estimated Hours</h6>
    <input type="text" class="form-control rounded-0" placeholder="Estimated Hours" formControlName="EstimatedHours" OnlyNumber>
</div>

OnlyNumber attribute directive

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

@Directive({
    selector: '[OnlyNumber]'
})
export class OnlyNumberDirective {

    constructor(private el: ElementRef) { }

    @HostListener('keydown', ['$event']) onKeyDown(event: KeyboardEvent) {
        let e = <KeyboardEvent>event;
        /* 
            8 -  for backspace
            9 -  for tab
            13 - for enter
            27 - for escape
            46 - for delete
        */
        if ([8, 9, 13, 27, 46].indexOf(e.keyCode) !== -1 ||
            // Allow: Ctrl+A
            (e.keyCode === 65 && (e.ctrlKey || e.metaKey)) ||
            // Allow: Ctrl+C
            (e.keyCode === 67 && (e.ctrlKey || e.metaKey)) ||
            // Allow: Ctrl+V
            (e.keyCode === 86 && (e.ctrlKey || e.metaKey)) ||
            // Allow: Ctrl+X
            (e.keyCode === 88 && (e.ctrlKey || e.metaKey)) ||
            // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
            // let it happen, don't do anything
            return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    }

    @HostListener('paste', ['$event']) blockPaste(event: KeyboardEvent) {
        this.validateFields(event);
    }
    validateFields(event) {
        let numberRegEx = /^[0-9]+$/;
        if(!numberRegEx.test(this.el.nativeElement.value)){
            this.el.nativeElement.value = "";
            event.preventDefault();
        }
    }
}

将此输入您的输入

Put this OnlyNumber="true"

<input type="text" class="form-control rounded-0" placeholder="Estimated Hours"  formControlName="EstimatedHours" OnlyNumber="true">