我在垫式表单字段中输入了内容:
<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
。
编辑:在堆栈中复制代码:https://stackblitz.com/edit/angular-7fxuqi?file=src/app/app.component.html
最佳答案
您可以使用RegularExpression
在数字中添加空格:
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
因为您的值有空格。所以在赋值之前,我们需要删除空格:
{{ myValue | formatSize }}<br>
<input type="text" [ngModel]="myValue | formatSize "
(ngModelChange)="removeWhitespace($event)"
placeholder="value" [ngModelOptions]="{standalone: true}">
typescript :
removeWhitespace(event) {
this.myValue = event.replace(/ /g,'');
}
关于angular - 更改值格式时输入中显示 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59088842/