首页 > 解决方案 > 指令不适用于非数值

问题描述

我有指令禁止在输入中输入非数字符号

这是指令

  import { NgControl } from "@angular/forms";
import { HostListener, Directive } from "@angular/core";

    @Directive({
      exportAs: "number-directive",
      selector: "number-directive, [number-directive]",
    })
    export class NumberDirective {
      private el: NgControl;
      constructor(ngControl: NgControl) {
        this.el = ngControl;
      }
      // Listen for the input event to also handle copy and paste.
      @HostListener("input", ["$event.target.value"])
      onInput(value: string): void {
        // Use NgControl patchValue to prevent the issue on validation
        this.el.control.patchValue(value.replace(/[^0-9]/g, "").slice(0));
      }
    }

这是我如何使用它input

  <input
  type="text"
  tabindex="0"
  class="search__input form-control-md + {{class}}"
  [value]="config.value"
  [required]="config.required"
  [attr.maxlength]="config.maxLength"
  [attr.minLength]="config.minLength"
  #inputElem
  number-directive
/>

但我仍然可以写aaaaa或任何文字

我的问题在哪里?

标签: javascriptangulartypescriptangular-directiveangular-decorator

解决方案


怀疑有两个根本原因:

  1. 忘记NumberDirectivedeclarations添加app.module.ts

    您需要添加NumberDirectiveapp.module.tsdeclarations来注册指令。

@NgModule({
  ...
  declarations: [..., NumberDirective],
})
export class AppModule {}
  1. NgControl您的<input>元素没有提供者。

    您将收到如下错误消息,因为[(ngModel)]输入元素缺失。该指令期望它是一个NgControl. 因此它需要有[(ngModel)].

    或者你需要[formControl]="configControl"你的<input>元素。

错误:R3InjectorError(AppModule)[NgControl -> NgControl -> NgControl]: NullInjectorError: No provider for NgControl!

<input
  type="text"
  tabindex="0"
  class="search__input form-control-md + {{ class }}"
  [value]="config.value"
  [required]="config.required"
  [attr.maxlength]="config.maxLength"
  [attr.minLength]="config.minLength"
  #inputElem
  number-directive
  [(ngModel)]="config.value"
/>

或者

<input
  type="text"
  tabindex="0"
  class="search__input form-control-md + {{ class }}"
  [value]="config.value"
  [required]="config.required"
  [attr.maxlength]="config.maxLength"
  [attr.minLength]="config.minLength"
  #inputElem
  number-directive
  [formControl]="configControl"
/>
configControl = new FormControl();

StackBlitz 上的示例解决方案


推荐阅读