问题描述
我正在尝试在我的Angular App中使用Directive,在输入框中,用户必须只能插入带有小数点后三位的值。
小数点之间用逗号分隔,但是在某些情况下,用户将使用点作为分隔符,在这种情况下,我必须在输入时用逗号替换点。
我正在尝试通过以下方式对其进行存档:
@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 ...
解决方法
根据parseFloat的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
Return value
A floating point number parsed from the given string.
Or NaN when the first non-whitespace character cannot be converted to a number.
Parsefloat需要一个字符串000.00
,但是因为您将.
替换为,
,所以得到了NaN。
我建议先解析该数字,然后转换为您的输出,并且仅在对值满意后才进行设置,而不是多次重置相同的值。
@Directive({
selector: '[appQuantity]',})
export class QuantityDirective {
@Input()
public plu: Plu;
constructor(private ref: ElementRef) {}
@HostListener('input',['$event'])
public onInput(event: any): void {
// Use `let` instead of rewriting the value constantly (weird side effects on ui if you keep setting the value)
let val = this.ref.nativeElement.value;
// Convert `,` to `.` to allow for valid parsing
val = parseFloat( val.replace(/,/g,'.'))
if (this.plu.um === 'PZ'){ // controls if input is empty i'm setting 1
// Now that `val` is a number,`<= 0` is valid because it should not be used on strings
if (!val || val <= 0){
val = 1;
}
}
// Format as needed
const correctFormat = val.toString().replace(/\./g,',')
// Set now
this.ref.nativeElement.value = correctFormat
this.plu.qta= correctFormat; // setting the object quantity to inserted value
}
}
只是一个提示
如果您担心数字格式,可以使用toLocaleString和其他内置数字formatters,这些数字可以处理货币和语言等内容。