Angular2 [(ngModel)]数字输入作为字符串值传递给TypeScript的数字属性

时间:2016-12-07 01:29:08

标签: typescript nativescript angular2-nativescript

我正在测试一个简单的计算器,该计算器应该总结2个数字,但它会将它们连接起来,尽管我声明了带有类型定义的属性。

如果我编码为+this.number1 + +this.number2,那就没关系。但是,有没有办法将它们从[(ngModel)]传递给typescript类作为数值?

我已经研究但找不到任何东西。我错过了什么吗?

app.component.html

`...
<TextField hint="Number 1" [(ngModel)]="number1" keyboardType="number"></TextField>
<TextField hint="Number 2" [(ngModel)]="number2" keyboardType="number"></TextField>
<Button text="Calculate" (tap)="calculate()"></Button>
...`

app.component.ts

...
public number1: number = 0;
public number2: number = 0;
public result: number = 0;

calculate(){
        this.result = this.number1 + this.number2;
        // if I code this as "this.result = +this.number1 + +this.number2;" it is working.
}
...

0 个答案:

没有答案