我想把一些数字写入<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/