Allow only numbers and decimal in textbox angular 10 code example

Example 1: accept 2 values after decimal in angular forms

import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
  selector: '[appTwoDigitDecimaNumber]'
})
export class TwoDigitDecimaNumberDirective {
  private regex: RegExp = new RegExp(/^\d*\.?\d{0,2}$/g);
  private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', '-', 'ArrowLeft', 'ArrowRight', 'Del', 'Delete'];
  constructor(private el: ElementRef) {
  }
  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    console.log(this.el.nativeElement.value);
    // Allow Backspace, tab, end, and home keys
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }
    let current: string = this.el.nativeElement.value;
    const position = this.el.nativeElement.selectionStart;
    const next: string = [current.slice(0, position), event.key == 'Decimal' ? '.' : event.key, current.slice(position)].join('');
    if (next && !String(next).match(this.regex)) {
      event.preventDefault();
    }
  }
}

Example 2: accept 2 values after decimal in angular forms

<input type="textbox" [(ngModel)]="InputValue" appTwoDigitDecimaNumber>

Example 3: 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();  }}

Example 4: 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);}