在我的项目中,select 的值有问题。我不知道为什么,select 只显示最后一个值,而值与输入的乘法显示了 NaN
结果。
另外我想问一下在不同的类(price
,priceAAB
)中区分priceFG
是否是最好的解决方案?因为我的两个类都具有相同的 value
(例如,priceAAB
没有 D0
和 D1
),但具有不同的 price
。这些选择应根据我将在页面顶部选择的 risk
类型显示
summary.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
}
summary.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
答案 0 :(得分:1)
这里有多个问题。
<input>
元素的值才能在控制器中重用它。最快的方法是使用 ngModel
双向绑定元素。<input type="number" [(ngModel)]="userNumber">
sum()
字段为空时调用 <input>
函数。<button class="btn btn-primary" [disabled]="!userNumber" (click)=sum()>Go
</button>
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
答案 1 :(得分:0)
您可能会得到 NaN,因为您没有在 sum() 函数中初始化数字?而不是这样做:let price: number
你应该这样做 let price: number = 0
吗?
此外,您应该使用 price = a.price
代替 price += a.price
吗?