Files
psp_panel/src/app/shared/components/input/price-input.component.ts
T

106 lines
3.1 KiB
TypeScript
Raw Normal View History

import { Maybe } from '@/core';
import { ToastService } from '@/core/services/toast.service';
import { UikitFieldComponent } from '@/uikit/uikit-field.component';
import { CommonModule } from '@angular/common';
import {
Component,
ContentChild,
EventEmitter,
inject,
Input,
Output,
TemplateRef,
} from '@angular/core';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { InputGroupModule } from 'primeng/inputgroup';
import { InputGroupAddon } from 'primeng/inputgroupaddon';
import { InputNumberInputEvent, InputNumberModule } from 'primeng/inputnumber';
@Component({
selector: 'app-price-input',
standalone: true,
imports: [
ReactiveFormsModule,
InputGroupModule,
InputGroupAddon,
InputNumberModule,
UikitFieldComponent,
CommonModule,
],
templateUrl: './price-input.component.html',
})
export class PriceInputComponent {
@Input() control!: FormControl<Maybe<any>>;
@Input() name!: string;
@Input() label = '';
@Input() placeholder?: string;
@Input() disabled = false;
@Input() size?: 'small' | 'large';
@Input() autocomplete: string = 'off';
@Input() showErrors = true;
@Input() hint?: string;
@Input() min?: number = 0;
@Input() max?: number;
@Input() required = false;
@Output() inputEvent = new EventEmitter<InputNumberInputEvent>();
@Output() blur = new EventEmitter<void>();
@ContentChild('suffixTemp', { static: true }) suffixTemp!: TemplateRef<any> | null;
private readonly toastService = inject(ToastService);
get preparedPlaceholder(): string {
return this.placeholder || 'مبلغ';
}
get isRequired(): boolean {
return this.required || this.control.hasValidator(Validators.required);
}
get sizeClass(): string {
return this.size === 'large' ? 'p-inputtext-lg' : this.size === 'small' ? 'p-inputtext-sm' : '';
}
onInput(event: InputNumberInputEvent) {
const eventValue = Number(event.value ?? 0);
const min = this.min ?? undefined;
const max = this.max ?? undefined;
const minValidator = min !== undefined && eventValue < min;
const maxValidator = max !== undefined && eventValue > max;
if (maxValidator) {
this.toastService.warn({
text: `مقدار ${this.label} نمی‌تواند بیشتر از ${this.max!.toLocaleString('en-US')} باشد.`,
});
}
if (minValidator) {
this.toastService.warn({
text: `مقدار ${this.label} نمی‌تواند کمتر از ${this.min!.toLocaleString('en-US')} باشد.`,
});
}
if (minValidator || maxValidator) {
const normalizedValue = parseFloat(
eventValue.toString().slice(0, eventValue.toString().length - 1) || '0'
);
this.control.setValue(normalizedValue);
// @ts-ignore
event.originalEvent.target.value = normalizedValue
? normalizedValue.toLocaleString('en-US')
: normalizedValue;
} else {
// @ts-ignore
event.originalEvent.target.value = eventValue
? eventValue.toLocaleString('en-US')
: eventValue;
}
this.inputEvent.emit({
...event,
value: eventValue,
});
}
}