Enter only numbers?

@Directive({
 selector: '[numbersOnly]'
})
export class OnlyNumberDirective {

 constructor(private _el: ElementRef) { }

 @HostListener('input', ['$event']) onInputChange(event) {
 const initialValue = this._el.nativeElement.value;

 this._el.nativeElement.value = initialValue.replace(/[^0-9]*/g, ");
 if ( initialValue !== this._el.nativeElement.value) {
event.the stoppropagation();
}
}
}

There is this Directive, which makes it possible to enter only numbers in the field. But, if you set the length for the field and start typing the first letter, the length will be equal to one(but the letters in the input will not be visible), then if you enter a digit, the length of all as a unit. Also, if you have a field with the number symbol = the maximum length, then remove one character and add a letter, then field is valid. How this problem can be solved?
April 3rd 20 at 17:37
1 answer
April 3rd 20 at 17:39
import { Directive } from '@angular/core';
import { NgControl } from '@angular/forms';
import { Subscription } from 'rxjs';

@Directive({
 selector: '[numbers]',
})
export class NumbersDirective {
 sub = new Subscription();

constructor(
 private ngControl: NgControl
 ) { }

 ngOnInit() {
 this.sub = this.ngControl.valueChanges.subscribe(value => {
this.ngControl.control.setValue(
 (value || ").replace(/[^0-9]*/g, "),
 { emitEvent: false },
)
});
}
 ngOnDestroy() {
this.sub.unsubscribe();
}
}

Find more questions by tags Angular