import { Directive, ElementRef, HostListener, Input } from '@angular/core'; import { ThousandSeparatorPipe } from '../../../pipes/thousand-separator.pipe'; @Directive({ selector: '[appMinMaxValue]', standalone: true, }) export class MinMaxValueDirective { @Input() minValue!: number; @Input() maxValue!: number; constructor( private el: ElementRef, private thousandSeparatorPipe: ThousandSeparatorPipe ) {} @HostListener('document:keypress', ['$event']) onKeyPress(event: KeyboardEvent) { const oldValue = this.el.nativeElement.value as string; const newKey = event.key; const currentPosition = this.el.nativeElement.selectionStart; const newValue = oldValue.slice(0, currentPosition) + newKey + oldValue.slice(currentPosition); const currentValue = parseFloat(newValue.replace(',', '')); if (currentValue < this.minValue) event.preventDefault(); if (currentValue > this.maxValue) { event.preventDefault(); this.el.nativeElement.value = this.thousandSeparatorPipe.transform( this.maxValue ); } } }