【问题标题】:multiply two figures with typescript read NaN将两个数字与打字稿相乘读取 NaN
【发布时间】:2018-03-20 08:32:51
【问题描述】:

我试图在数量值更改后获取总价,但它在控制台上读取 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>

【问题讨论】:

    标签: javascript angular ionic2


    【解决方案1】:

    尝试使用 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) ;
    }
    

    【讨论】:

    • 我忘记将 ngModel 附加到数量文本框
    【解决方案2】:

    您在 &lt;ion-input&gt; 中缺少用于数量的 ngModel 指令。所以,this.quantity 永远不会更新,我认为它是undefined。所以最后你乘以一个数字和undefined

    5 * undefined = NaN
    

    你得到了什么。

    【讨论】:

      【解决方案3】:

      当数量变化事件时,您将调用 getTotal 并使用this.quantity 来计算它。但是,this.quantity 不会在输入中用作值的绑定。

      <ion-item>
        <ion-label>Quantity</ion-label>
        <ion-input (ionChange)="getTotal()" type="number" [(ngModel)]="quantity"></ion-input>
      </ion-item>
      

      【讨论】:

        猜你喜欢
        • 2022-08-21
        • 2023-01-28
        • 2010-12-24
        • 2019-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-01
        • 1970-01-01
        相关资源
        最近更新 更多