Reputation: 875
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?
Upvotes: 2
Views: 6709
Reputation: 55443
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);
}
}
Upvotes: 3