typescript - 使用数字管道抛出 InvalidPipeArgumentException(管道 '1' 的无效参数 'DecimalPipe')

标签 typescript angular angular2-template angular2-pipe

我想把一些数字写入<input>并在 {{}} 中动态显示为小数通过管道。它会抛出异常。这是我的代码:

app.template.html:

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

应用程序组件.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)"/>

应用程序组件.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 旁边非常重要,是什么使得从字符串到数字的转换成为可能!

最佳答案

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

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

这意味着,您实际上需要传递一个数字类型的变量。使用 input 并像您在那里那样绑定(bind)到 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" />

关于typescript - 使用数字管道抛出 InvalidPipeArgumentException(管道 '1' 的无效参数 'DecimalPipe'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38461080/

相关文章:

Angular 无法定位样式表警告

unit-testing - Angular 2 单元测试 : Custom Pipe error The pipe could not be found

css - Angular 2 更改位置以固定在滚动条上

angular - 错误 : No NgModule metadata found for '[object Object]'

css - Angular Renderer2 无法添加类

javascript - 操作 Angular 2 中 HTML 元素的位置

angular - 在 ng-template 中使用 ng-content

angular - 如何使用 Angular 2 为不同的环境加载不同的全局 css 样式

typescript - 在 Typescript 中获取泛型类型参数的名称

javascript - Angular 4选中多个复选框