import { Directive, ElementRef, HostListener, Input, OnInit, } from '@angular/core'; @Directive({ selector: '[positiveNumbers]', }) export class PositiveNumbersDirective implements OnInit { @Input() public minAttribute: number = 0; private _regex: RegExp = new RegExp(/^[0-9]+(\.[0-9]*){0,1}$/g); private _specialKeys = [ 'Backspace', 'Tab', 'End', 'Home', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', ]; constructor( private _elementRef: ElementRef, ) {} public ngOnInit() { this._elementRef.nativeElement.setAttribute('min', this.minAttribute); } @HostListener('keydown', ['$event']) public keydown(event: KeyboardEvent) { if (this._specialKeys.some((key) => key === event.key)) { return; } const current = ( this._elementRef.nativeElement as HTMLInputElement).value; const next = current.concat(event.key); if (next && !next.match(this._regex)) { event.preventDefault(); } } }