angular 2 allow only numbers and one dot input 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('keydown', ['$event'])onKeyDown(e: KeyboardEvent) {  if (    // Allow: Delete, Backspace, Tab, Escape, Enter, etc    this.navigationKeys.indexOf(e.key) > -1 ||     (e.key === 'a' && e.ctrlKey === true) || // Allow: Ctrl+A    (e.key === 'c' && e.ctrlKey === true) || // Allow: Ctrl+C    (e.key === 'v' && e.ctrlKey === true) || // Allow: Ctrl+V    (e.key === 'x' && e.ctrlKey === true) || // Allow: Ctrl+X    (e.key === 'a' && e.metaKey === true) || // Cmd+A (Mac)    (e.key === 'c' && e.metaKey === true) || // Cmd+C (Mac)    (e.key === 'v' && e.metaKey === true) || // Cmd+V (Mac)    (e.key === 'x' && e.metaKey === true) // Cmd+X (Mac)  ) {    return;  // let it happen, don't do anything  }  // Ensure that it is a number and stop the keypress  if (e.key === ' ' || isNaN(Number(e.key))) {    e.preventDefault();  }}