首页 > 解决方案 > 角度选择和的 NaN 总值

问题描述

在我的项目中,我对选择的值有疑问。我不知道为什么,选择只显示最后一个值,将值与输入相乘显示NaN结果。另外我想问一下区分price不同的类(priceAAB, priceFG)是否是最好的解决方案?因为我有两个相等的类valuepriceAAB例如没有D0and D1),但不同的price. 这些选择应根据risk我要在页面顶部选择的类型显示

摘要.ts

//risk: string = "C"
  risk: string = "D"
  userNumber: number
  intoSelectPrice: number = 0
  total: number = 0
  

  priceAAB: PriceAAB[] = [
    { id: 1, value: "D2", price: 240 },
    { id: 2, value: "D3", price: 840 },
    { id: 3, value: "D4", price: 1200 },
    { id: 4, value: "D5", price: 1200 }
  ]

  priceFG: PriceFG[] = [
    { id: 1, value: "D0", price: 840 },
    { id: 2, value: "D1", price: 840 },
    { id: 1, value: "D2", price: 1080 },
    { id: 2, value: "D3", price: 1200 },
    { id: 3, value: "D4", price: 1200 },
    { id: 4, value: "D5", price: 1200 }
  ]

  sum() {
    if(this.risk == "C") {
      let price: number
      this.priceAAB.forEach(a => {
          price = a.price
      })
      this.intoSelectPrice = price
      this.total = price * this.userNumber
    } else if(this.risk == "D") {
      let price: number
      this.priceFG.forEach(a => {
          price = a.price
      })
      this.intoSelectPrice = price
      this.total = price * this.userNumber
    }
  }
  
}

export class PriceAAB {
  id: number
  value: string
  price: number
}

export class PriceFG {
  id: number
  value: string
  price: number
}

摘要.html

<input type="number" [value]="userNumber">mq

<select *ngIf="risk == 'C'">
  <option [ngValue]="array.price" *ngFor="let array of priceAAB">{{array.value}}: {{array.price}}
  </option>
</select>
<select *ngIf="risk == 'D'">
  <option [ngValue]="array.price" *ngFor="let array of priceFG">{{array.value}}: {{array.price}}
  </option>
</select>

<button class="btn btn-primary" (click)=sum()>Go
</button>
<br>
Number in select: {{intoSelectPrice}}<br>
Total: {{total}}

我还添加了 stackblitz 的链接 --> DEMO

标签: javascripthtmlarraysangulartypescript

解决方案


这里有多个问题。

  1. 您需要绑定模板<input>元素中的值以在控制器中重用它。最快的方法是使用ngModel.
<input type="number" [(ngModel)]="userNumber">
  1. 实现某种形式的验证以防止在字段为空sum()时调用该函数。<input>
<button class="btn btn-primary" [disabled]="!userNumber" (click)=sum()>Go
</button>
  1. sum()可以使用而不是执行求和来简化Array#reduce函数forEach
sum() {
  const priceSelected = this.risk == "C" ? this.priceAAB : this.priceFG;
  this.intoSelectPrice = priceSelected.reduce((acc, curr) => (acc += curr.price), 0);
  this.total = this.intoSelectPrice * this.userNumber;
}

我已经调整了你的Stackblitz


推荐阅读