2

考虑以下组件

import {Component} from 'angular2/core'

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <h3>Input with two decimals</h3>
      <input type="text" 
             [value]="formattedN" 
             (change)="nChanged($event.target.value)"/>
    </div>
  `,
  directives: []
})
export class App {

  private n: number = 0;
  private formattedN: string = "0.00"

  public nChanged(value) {
    this.n = parseFloat(value);
    this.formattedN = this.n.toFixed(2);
  }

}

输入应始终是带有两位小数的数字。然而,情况并非总是如此。尝试删除最后一个零,该字段不会更改为我想要的 0.00。我知道它不起作用,因为 formattedN 值没有更新,这意味着属性绑定没有更新,因此输入的值没有更新。

在 plunker 中运行示例:http: //plnkr.co/edit/Vyi4RKladslrdZslZQhm

有没有人有一个很好的解决这个问题的方法?

4

1 回答 1

3

这 是您要完成的 答案吗????

//our root app component
import {Component} from 'angular2/core'

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <input type="text" [(ngModel)]="formattedN" (change)="nChanged($event.target.value)"/>
    </div>
  `,
  directives: []
})
export class App {

  private n: number = 0;
  private formattedN: string = "0.00"

  constructor() {
    this.name = 'Angular2'
  }

  public nChanged(value) {
    console.log(value);
    this.n = parseFloat(value);
    console.log(this.n);
    this.formattedN = this.n.toFixed(2)
    console.log(this.formattedN);
  }
}
于 2016-03-06T04:55:00.963 回答