简体   繁体   中英

Force update of a property binding in angular 2

Consider the following component

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);
  }

}

The input should always be a number with two decimals. That is however not always the case. Try removing the last zero, the field is not changed to 0.00 which is what I want. I understand it doesn't work because the formattedN value is not updated, which means that the property binding is not updated, hence the value of the input is not updated.

Run the example in plunker: http://plnkr.co/edit/Vyi4RKladslrdZslZQhm

Does anyone have a nice solution for this problem?

Is this Answer what you're trying to accomplish????

//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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM