I've encountered some issues with the default behavior of the HTML number input and I'm looking to create a simple input that only allows numbers.
To address this, I have developed a directive as shown below:
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: 'input[numbersOnly]'
})
export class NumberDirective {
constructor(private _el: ElementRef) { }
@HostListener('input', ['$event']) onInputChange(event) {
const initalValue = this._el.nativeElement.value;
this._el.nativeElement.value = initalValue.replace(/[^0-9]*/g, '');
if (initalValue !== this._el.nativeElement.value) {
event.stopPropagation();
}
}
}
Despite using "event.stopPropagation()", I find that the event still propagates even when the input value remains unchanged from the user's perspective.
How can I prevent event propagation when the field value hasn't changed?
Edit: To provide better clarity, here is a StackBlitz example: https://stackblitz.com/edit/angular-numbers-only-directive