【发布时间】: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