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, ''); // get a digit-only string  document.execCommand('insertText', false, pastedInput);}@HostListener('drop', ['$event'])onDrop(event: DragEvent) {  event.preventDefault();  const textData = event.dataTransfer    .getData('text').replace(/\D/g, '');  this.inputElement.focus();  document.execCommand('insertText', false, textData);}