Tengo una directiva para prohibir ingresar símbolos no numéricos en la entrada
Aquí está la directiva
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)); } } Así es como lo uso en 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 /> Pero todavía puedo escribir aaaaa o cualquier palabra.
¿Dónde puede estar mi problema?
Sospecha de dos causas fundamentales:
Olvidé agregar NumberDirective a las declarations de app.module.ts .
Debe agregar NumberDirective a las declarations de app.module.ts para registrar la directiva.
@NgModule({ ... declarations: [..., NumberDirective], }) export class AppModule {} No hay proveedor para NgControl para su elemento <input> .
Recibirá el siguiente mensaje de error como faltante [(ngModel)] para el elemento de entrada. La directiva espera que sea un NgControl . Por lo tanto, debe tener [(ngModel)] .
O necesita [formControl]="configControl" para su elemento <input> .
Error: R3InjectorError(AppModule)[NgControl -> NgControl -> NgControl]: NullInjectorError: ¡No hay proveedor para 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" />O
<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();