import { Directive, ElementRef, HostListener, Input, } from '@angular/core'; @Directive({ selector: '[inputDecimalPlaces]', }) export class InputDecimalPlacesDirective { @Input() public maxNumbers = 5; @Input() public maxDecimalPoints = 2; private get _regex(): RegExp { const regex = `^(\\d{0,${this.maxNumbers}}\\.?` + `\\d{0,${this.maxDecimalPoints}}?)$`; return new RegExp(regex); } private _specialKeys = [ 'Backspace', 'Tab', 'End', 'Home', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', ]; constructor( private _elementRef: ElementRef, ) {} @HostListener('keydown', ['$event']) public keydown(event: KeyboardEvent) { const elementRef = this._elementRef.nativeElement as HTMLInputElement; const hasLongerThan1Selection = Boolean( elementRef.selectionStart != null && (elementRef.selectionEnd - elementRef.selectionStart > 0), ); if ( this._specialKeys.some((key) => key === event.key) || hasLongerThan1Selection ) { return; } const current = elementRef.value; const next = current.concat(event.key); if (next && !next.match(this._regex)) { event.preventDefault(); } } }