问题描述
我不理解Typescript和Angular的这种行为.
I don't understand this behaviour with Typescript and Angular.
my-component.html
<ion-select [(ngModel)]="creditAmount"
(ngModelChange)="onChangeCreditAmount()">
<ion-option value="25" selected="true">25€</ion-option>
<ion-option value="50">50€</ion-option>
<ion-option value="75">75€</ion-option>
<ion-option value="100">100€</ion-option>
</ion-select>
my-component.ts
creditAmount: number;
constructor() {
this.creditAmount = 25;
console.log(this.creditAmount);
}
onChangeCreditAmount() {
console.log(this.creditAmount);
}
在构造函数中,creditAmount是一个数字.在 onChangeCreditAmount
方法中,它变成了一个字符串.
In the constructor, creditAmount is a number. In the onChangeCreditAmount
method, it became a string.
我发现的唯一解决方法是使用显式强制转换: Number(this.creditAmount)
,但这对我来说似乎很棘手.有没有更好的办法 ?谢谢.
The only workaround I found is to use explicit cast: Number(this.creditAmount)
but this seems hacky to me. Is there a better way ? Thanks.
推荐答案
Typescript仅有助于编译时.结果仍然是一些JavaScript,这不是类型安全的.因此,您可以为 creditAmount
分配一个数字,一个字符串,一个数组或任何您喜欢的东西.
Typescript only helps on compile time. The result will still be some JavaScript, which is not type safe. So you can assign creditAmount
a number, a string, an array or whatever you like.
NgModel
似乎仅适用于字符串,因此如果需要数字,则必须对其进行解析.抱歉:-(
NgModel
seems to work with strings only, so you have to parse it if you need a number. Sorry :-(
这篇关于使用NgModel绑定,数字变为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!