I need help with a directive that restricts non-numeric symbols in an input field.
Below is the code for the directive:
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;
}
@HostListener("input", ["$event.target.value"])
onInput(value: string): void {
this.el.control.patchValue(value.replace(/[^0-9]/g, "").slice(0));
}
}
Here is an example of how to use it in an input
field:
<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
/>
Even after implementing the directive, I can still input text like aaaaa
. What could be causing this issue?