使用数字管道抛出 InvalidPipeArgumentException(管道参数“1”无效 'DecimalPipe')

Using number pipe throws InvalidPipeArgumentException (Invalid argument '1' for pipe 'DecimalPipe')

我想将一些数字写入 <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;
}

笨蛋: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 旁边的 + 非常重要,是什么使得从字符串到数字的转换成为可能!

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

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

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

Remember: type hints are only visible in TypeScript. After transpiling to JavaScript you lose that information

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

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

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