【问题标题】:Using number pipe throws InvalidPipeArgumentException (Invalid argument '1' for pipe 'DecimalPipe')使用数字管道会引发 InvalidPipeArgumentException(管道“DecimalPipe”的参数“1”无效)
【发布时间】:2016-11-22 11:58:36
【问题描述】:

我想将一些数字写入<input> 并通过管道将其动态显示为{{}} 内的小数。它会引发异常。这是我的代码:

app.template.html:

<h1>amount = {{amount|number:'1.2-2'}}</h1>
<input [(ngModel)]="amount"/>

app.component.ts:

import {Component} from '@angular/core';
@Component({
  selector: 'my-app',
  templateUrl: 'app/app.template.html'
})
export class AppComponent {
  private amount:number;
}

Plunker:http://plnkr.co/edit/I7ynnwBX4DWJfHNPIPRu?p=preview

在输入中写入任意数字,然后查看控制台中抛出的异常。


编辑:

根据 rinukkusu 建议的工作代码:

app.template.html:

<h1>amount = {{amount|number:'1.2-2'}}</h1>
<input [ngModel]="amount" (ngModelChange)="onChange($event)"/>

app.component.ts:

import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  templateUrl: 'app/app.template.html'
})
export class AppComponent {
  private amount:number;

  onChange($event) {
    this.amount = +$event;
  }
}

$event 旁边的 + 非常重要,是什么使从字符串到数字的转换成为可能!

【问题讨论】:

    标签: typescript angular angular2-template angular2-pipe


    【解决方案1】:

    查看 Angular 2 的源代码我发现了这个:

    if (!isNumber(value)) {
      throw new InvalidPipeArgumentException(pipe, value);
    }
    

    这意味着,您实际上需要传递一个数字类型的变量。使用 input 并绑定到 ngModel 就像你在那里所做的那样,你的 amount 变量将始终是字符串类型。

    记住:类型提示仅在 TypeScript 中可见。转译后 对于 JavaScript,您会丢失该信息

    我建议实施一个新的管道,将您的变量即时转换为数字:

    @Pipe({
        name: 'toNumber'
    })
    export class ToNumberPipe implements PipeTransform {
        transform(value: string):any {
            let retNumber = Number(value);
            return isNaN(retNumber) ? 0 : retNumber;
        }
    }
    

    你可以这样使用它:

    <h1>amount = {{amount | toNumber | number:'1.2-2'}}</h1>
    <input [(ngModel)]="amount" />
    

    【讨论】:

    • 你试过了吗? AFAIR +xxx(一元加号)在模板中不起作用,仅在代码中起作用。
    • 实际上没有 - 我认为他们可以工作哈哈。如果它们不起作用,我会尝试编辑我的答案!
    • 好的,所以它不起作用,就像@GünterZöchbauer 说的那样。我用一种新方法更新了我的答案,这比使用绑定变量更合适,因为如果您在更改时更改绑定变量,输入也会更改,这会让用户感到困惑。
    【解决方案2】:

    按照上面 rinukkusu 的解决方案——我能够在不创建自定义管道的情况下做到这一点。我刚刚使用了&lt;input [(ngModel)]="Number(amount)|number:'1.2-2'"/&gt;,它对我有用。

    【讨论】:

    • 我正在使用 angular 6 并尝试了这个但得到 .Number 不是函数
    • @goneos,您可以通过在 ts 中设置属性,如 Number = Number,使模板可以访问 Number
    猜你喜欢
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 2016-06-23
    • 1970-01-01
    • 2021-06-01
    • 2018-08-28
    • 2020-09-11
    相关资源
    最近更新 更多