将两个数字与打字稿相乘读取 NaN
multiply two figures with typescript read NaN
我试图在数量值更改后获取总价,但它在控制台读取的是 NaN
JS
getTotal(){
this.totalPrice= (this.price) * (this.quantity) ;
console.log(this.totalPrice)
}
HTML
<ion-item>
<ion-label>Price</ion-label>
<ion-input type="number" [(ngModel)]="price"></ion-input>
</ion-item>
<ion-item>
<ion-label>Quantity</ion-label>
<ion-input (ionChange)="getTotal()" type="number"></ion-input>
</ion-item>
<ion-item>
<ion-label>Total</ion-label>
<ion-input type="number" [(ngModel)]="totalPrice"></ion-input>
</ion-item>
您在 <ion-input>
中缺少 ngModel
数量指令。所以,this.quantity
永远不会更新,我假设它是 undefined
。所以最后你乘以一个数字和 undefined
和
5 * undefined = NaN
这就是你得到的。
尝试使用 getter:
HTML
<ion-item>
<ion-label>Price</ion-label>
<ion-input type="number" [(ngModel)]="price"></ion-input>
</ion-item>
<ion-item>
<ion-label>Quantity</ion-label>
<ion-input [(ngModel)]="quanity" type="number"></ion-input>
</ion-item>
<ion-item>
<ion-label>Total</ion-label>
<ion-input type="number" [(ngModel)]="totalPrice"></ion-input>
</ion-item>
打字稿:
get totalPrice(){
return (this.price) * (this.quantity) ;
}
当数量获取变化事件时,您将调用 getTotal 并使用 this.quantity
来计算它。但是,this.quantity 未在输入中用作值的绑定。
<ion-item>
<ion-label>Quantity</ion-label>
<ion-input (ionChange)="getTotal()" type="number" [(ngModel)]="quantity"></ion-input>
</ion-item>
我试图在数量值更改后获取总价,但它在控制台读取的是 NaN
JS
getTotal(){
this.totalPrice= (this.price) * (this.quantity) ;
console.log(this.totalPrice)
}
HTML
<ion-item>
<ion-label>Price</ion-label>
<ion-input type="number" [(ngModel)]="price"></ion-input>
</ion-item>
<ion-item>
<ion-label>Quantity</ion-label>
<ion-input (ionChange)="getTotal()" type="number"></ion-input>
</ion-item>
<ion-item>
<ion-label>Total</ion-label>
<ion-input type="number" [(ngModel)]="totalPrice"></ion-input>
</ion-item>
您在 <ion-input>
中缺少 ngModel
数量指令。所以,this.quantity
永远不会更新,我假设它是 undefined
。所以最后你乘以一个数字和 undefined
和
5 * undefined = NaN
这就是你得到的。
尝试使用 getter:
HTML
<ion-item>
<ion-label>Price</ion-label>
<ion-input type="number" [(ngModel)]="price"></ion-input>
</ion-item>
<ion-item>
<ion-label>Quantity</ion-label>
<ion-input [(ngModel)]="quanity" type="number"></ion-input>
</ion-item>
<ion-item>
<ion-label>Total</ion-label>
<ion-input type="number" [(ngModel)]="totalPrice"></ion-input>
</ion-item>
打字稿:
get totalPrice(){
return (this.price) * (this.quantity) ;
}
当数量获取变化事件时,您将调用 getTotal 并使用 this.quantity
来计算它。但是,this.quantity 未在输入中用作值的绑定。
<ion-item>
<ion-label>Quantity</ion-label>
<ion-input (ionChange)="getTotal()" type="number" [(ngModel)]="quantity"></ion-input>
</ion-item>