allow only numbers in textbox angular 10 code example
Example 1: textbox should accept only numbers till 10 digit using angular
<input type="text" name="country_code" title="Error Message" pattern="[1-9]{1}[0-9]{9}">
Example 2: angular numbers only directive
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: 'input[type=number], input[numbersOnly]'
})
export class NumbersOnlyInputDirective {
constructor(private elRef: ElementRef) { }
@HostListener('input', ['$event']) onInputChange(event) {
const initalValue = this.elRef.nativeElement.value;
this.elRef.nativeElement.value = initalValue.replace(/[^0-9]*/g, '');
if ( initalValue !== this.elRef.nativeElement.value) {
event.stopPropagation();
}
}
}