【问题标题】:NaN displayed in input when changing format of value更改值格式时在输入中显示 NaN
【发布时间】:2019-11-28 12:23:51
【问题描述】:

我在一个垫子表单字段中输入了我的输入:

<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

【问题讨论】:

    标签: angular input format nan


    【解决方案1】:

    你可以使用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}">
    

    打字稿:

    removeWhitespace(event) {    
        this.myValue = event.replace(/ /g,'');
    }
    

    【讨论】:

    • 不能在类型号上使用replace
    • 还是不行,如果是 > 9999 @StepUp,则在 DOM 中显示 NaN
    • @sowebull 你能创建一个stackbliz 的例子吗?
    • 注意:如果你复制这个 89009789 并将其直接粘贴到输入中,它将起作用。
    【解决方案2】:

    它不会那样工作。你必须使用某种面具解决方案。这是一条充满痛苦和痛苦的道路,最流行的解决方案是https://github.com/text-mask/text-mask

    我经常使用它,虽然它有很多问题,但它是可以使用的。

    【讨论】:

    • 最好不要为此使用库
    • 你不能。为了得到你想要的,你需要插入符号位置管理解决方案,而不仅仅是类型转换和格式化。
    • 什么意思?它是一个用于多个框架的库。还打包了一个角度指令。
    猜你喜欢
    • 2016-11-19
    • 2018-11-26
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 2022-01-20
    • 1970-01-01
    相关资源
    最近更新 更多