javascript - 角度选择和的 NaN 总值
问题描述
在我的项目中,我对选择的值有疑问。我不知道为什么,选择只显示最后一个值,将值与输入相乘显示NaN
结果。另外我想问一下区分price
不同的类(priceAAB
, priceFG
)是否是最好的解决方案?因为我有两个相等的类value
(priceAAB
例如没有D0
and 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
解决方案
这里有多个问题。
- 您需要绑定模板
<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
推荐阅读
- amazon-web-services - AWS Lambda 无法识别来自 js-sdk 的 sagemaker 服务的功能
- angular - 在 IE 11 中加载应用程序时,它会在控制台上抛出错误提示 - SCRIPT5007: Unable to get property 'fn' of undefined or null reference
- sql-server-2008 - 使用 SQL Server Join 拆分值并与表进行比较
- asp.net-mvc - 在“/”应用程序中出现服务器错误
- delphi - 在 TWebBrowser 控件中检测服务器端重定向
- swift - Vapor 3:一个应用程序中的多个服务器套接字
- angular - 为什么 Angular 不在其应用程序 angular.io 中使用 Angular 的路由器模块?
- java - 使用 org.jboss.dmr.ModelNode 更改数据源属性
- c# - C# Wix 服务安装程序 - 未解决的符号引用
- php - Laravel-查询以获取父母和所有可能的孩子