import { Directive, ElementRef, HostListener, Input } from '@angular/core'; @Directive({ selector: '[appMaxValue]', standalone: true, }) export class MaxValueDirective { @Input() appMaxValue?: number; // Max allowed value constructor(private el: ElementRef) {} @HostListener('applyMaxValueDirective', ['$event']) onInput(event: Event): void { if (!this.appMaxValue) return; const input = event.target as HTMLInputElement; let value = input.value; // Remove thousands separators (`,`) before parsing let numericValue = parseFloat(value.replace(/,/g, '')); //If value exceeds the max, revert to max value if (!isNaN(numericValue) && numericValue > this.appMaxValue!) { input.value = this.formatNumber(this.appMaxValue!); event.preventDefault(); } } @HostListener('blur', ['$event']) onBlur(event: Event): void { const input = event.target as HTMLInputElement; let numericValue = parseFloat(input.value.replace(/,/g, '')); const dotIndex = input.value.indexOf('.'); if (!isNaN(numericValue) && dotIndex > 0) { input.value = this.formatNumber(numericValue); // Format correctly on blur } } // Helper function to format number with thousands separator private formatNumber(value: number): string { return value.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2, }); } }