angular input type text only number directive code example
Example 1: 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();
}
}
}
Example 2: numeric key angular validation
@HostListener('paste', ['$event'])onPaste(event: ClipboardEvent) { event.preventDefault(); const pastedInput: string = event.clipboardData .getData('text/plain') .replace(/\D/g, '');