【发布时间】:2023-03-23 21:17:01
【问题描述】:
我正在尝试在我的 Angular 应用程序中使用指令,在输入框中,用户必须能够仅插入三位小数的值。
小数点用逗号分隔,但可能存在用户使用点作为分隔符的情况,在这种情况下,我必须在输入时用逗号替换点。
我正在尝试以下方式来归档它:
@Directive({
selector: '[appQuantity]',
})
export class QuantityDirective {
@Input()
public plu: Plu;
constructor(private ref: ElementRef) {}
@HostListener('input', ['$event'])
public onInput(event: any): void {
const val = this.ref.nativeElement.value;
this.ref.nativeElement.value = this.ref.nativeElement.value.replace(/\./g, ','); // here i should replace dot with comma but it's not working
if (this.plu.um === 'PZ'){ // controls if input is empty i'm setting 1
if (!val || val <= 0){
this.ref.nativeElement.value = 1;
}
}
this.plu.qta = parseFloat(this.ref.nativeElement.value); // setting the object quantity to inserted value
}
}
但它只是在 parseFloat 上返回 NaN 值并将输入设置为 1...
【问题讨论】:
标签: angular typescript angular-directive