angular - 更改值格式时输入中显示 NaN

标签 angular input format nan

我在垫式表单字段中输入了内容:

<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/

相关文章:

javascript - 使用 JavaScript 只接受 1 到 9 的数字

python - 如何验证时间格式?

angular - 如何在vmware-clarity,Angular6中将sidenav导航链接的默认状态设置为关闭

Angular:ControlValueAccessor vs @Input - 什么时候用表单?

Angular:将函数传递给对象内部的服务

c - 格式字符串中的 %p 与 %x

c - 使用 "%c%c..."格式说明符打印字符串会产生不稳定的结果。为什么会这样?

typescript - Angular2 合并可观察对象

javascript - 如何创建一个 N :N relation editor in web page?

java - 检查输入到数组中的输入是否正确/不正确