import { Directive, ElementRef, HostListener, Input } from '@angular/core'; @Directive({ selector: '[priceFormat]', standalone: true, }) export class PriceFormatDirective { constructor(private el: ElementRef) {} @Input() priceSeparator?: boolean = false; // Default is false @HostListener('input', ['$event']) onInput(event: Event): void { if (!this.priceSeparator) return; // Skip if disabled let input = this.el.nativeElement; let value = input.value; // Allow only numbers and one dot (.) value = value.replace(/[^0-9.]/g, ''); const [integerPart, decimalPart] = value.split('.'); // Ensure decimal part is limited to two places if (decimalPart && decimalPart.length > 2) { value = integerPart + '.' + decimalPart.substring(0, 2); } // Apply thousands separator formatting input.value = this.formatWithCommas(value); } private formatWithCommas(value: string): string { return value.replace(/\B(?=(\d{3})+(?!\d))/g, ','); // Format whole number } }