更改值格式时在输入中显示 NaN
NaN displayed in input when changing format of value
我在垫子表单字段中输入了我的信息:
<mat-form-field style="padding-right: 10px;">
<input matInput type="text" [ngModel]="value | formatSize" (ngModelChange)="value=+$event";
placeholder="value" [ngModelOptions]="{standalone: true}">
</mat-form-field>
我的烟斗
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'formatSize'})
export class FormatSize implements PipeTransform {
transform(value: number) {
return value.toLocaleString();
}
}
我的目标是显示格式如下的值:
1000 -> 1000
10000 -> 10000
...
我的代码的问题是,当我输入一个大于 9999 的值时,它会在我的输入中显示 NaN,而我的值在我的组件中是 ǹull
。
EDIT:在堆栈中复制代码:https://stackblitz.com/edit/angular-7fxuqi?file=src/app/app.component.html
这样不行。你必须使用某种面具解决方案。这是一条充满痛苦和痛苦的道路,最受欢迎的解决方案是 https://github.com/text-mask/text-mask
我经常使用它,虽然它有很多问题,但还是可以使用的。
您可以使用 RegularExpression
将 space 添加到数字中:
const spaces = n => String(n)
.replace(
/(?!^)(?=(?:\d{3})+$)/g,
' '
);
const numbers = [10, 1000, 10000, 100000, 1000000, 10000000]
numbers.forEach(f => console.log(spaces(f)))
代码在您的管道中应如下所示:
@Pipe({name: 'formatSize'})
export class FormatSize implements PipeTransform {
transform(value: number) {
return String(value).replace(
/(?!^)(?=(?:\d{3})+$)/g,
' '
);
}
}
更新:
你有 NaN
因为你的值有 space。所以在赋值之前,我们需要去掉whitespades:
{{ myValue | formatSize }}<br>
<input type="text" [ngModel]="myValue | formatSize "
(ngModelChange)="removeWhitespace($event)"
placeholder="value" [ngModelOptions]="{standalone: true}">
打字稿:
removeWhitespace(event) {
this.myValue = event.replace(/ /g,'');
}
我在垫子表单字段中输入了我的信息:
<mat-form-field style="padding-right: 10px;">
<input matInput type="text" [ngModel]="value | formatSize" (ngModelChange)="value=+$event";
placeholder="value" [ngModelOptions]="{standalone: true}">
</mat-form-field>
我的烟斗
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'formatSize'})
export class FormatSize implements PipeTransform {
transform(value: number) {
return value.toLocaleString();
}
}
我的目标是显示格式如下的值:
1000 -> 1000
10000 -> 10000
...
我的代码的问题是,当我输入一个大于 9999 的值时,它会在我的输入中显示 NaN,而我的值在我的组件中是 ǹull
。
EDIT:在堆栈中复制代码:https://stackblitz.com/edit/angular-7fxuqi?file=src/app/app.component.html
这样不行。你必须使用某种面具解决方案。这是一条充满痛苦和痛苦的道路,最受欢迎的解决方案是 https://github.com/text-mask/text-mask
我经常使用它,虽然它有很多问题,但还是可以使用的。
您可以使用 RegularExpression
将 space 添加到数字中:
const spaces = n => String(n)
.replace(
/(?!^)(?=(?:\d{3})+$)/g,
' '
);
const numbers = [10, 1000, 10000, 100000, 1000000, 10000000]
numbers.forEach(f => console.log(spaces(f)))
代码在您的管道中应如下所示:
@Pipe({name: 'formatSize'})
export class FormatSize implements PipeTransform {
transform(value: number) {
return String(value).replace(
/(?!^)(?=(?:\d{3})+$)/g,
' '
);
}
}
更新:
你有 NaN
因为你的值有 space。所以在赋值之前,我们需要去掉whitespades:
{{ myValue | formatSize }}<br>
<input type="text" [ngModel]="myValue | formatSize "
(ngModelChange)="removeWhitespace($event)"
placeholder="value" [ngModelOptions]="{standalone: true}">
打字稿:
removeWhitespace(event) {
this.myValue = event.replace(/ /g,'');
}