Директива не работает для нечисловых значений

#javascript #angular #typescript #angular-directive #angular-decorator

Вопрос:

У меня есть директива, запрещающая вводить нечисловые символы при вводе

Вот директива

   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 или какие-либо слова

Где может быть моя проблема?

Ответ №1:

Подозреваю две основные причины:

  1. Забыл добавить NumberDirective в declarations для app.module.ts.

    Вам нужно добавить NumberDirective в declarations для app.module.ts, чтобы зарегистрировать директиву.

 @NgModule({
  ...
  declarations: [..., NumberDirective],
})
export class AppModule {}
 
  1. Нет поставщика NgControl для вашего <input> элемента.

    Вы получите сообщение об ошибке, как показано ниже, как отсутствующее [(ngModel)] для элемента ввода. Директива ожидает, что это будет NgControl . Следовательно, это необходимо иметь [(ngModel)] .

    Или вам нужна [formControl]="configControl" ваша <input> стихия.

Ошибка: R3InjectorError(AppModule)[ngControl -> ngControl ->> ngControl]: Ошибка NullInjectorError: Нет поставщика для 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();
 

Образец решения на СтекбЛитце

Комментарии:

1. Я не использую ngModel, я использую формы и элементы управления формами. Может быть, здесь есть проблема?

2. Да, бинго, тебе нужно [formControl]='configControl' .