angular 2 allow only numbers and one dot site 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, '');