Angular11中如何实现点击复选框动态更新响应的minValue与maxValue
实现步骤&代码示例
1. 先定义类型声明
// 单条成本条目类型 interface CostItem { MinValue: number MaxValue: number } // 接口返回的完整数据类型 interface CostResponse { DataNeeded: CostItem[] Resources: CostItem[] } // 条目分类枚举,用来区分两类数据 type ItemCategory = 'DataNeeded' | 'Resources'
2. 核心逻辑实现
我们用Set存储选中项的唯一标识(格式为分类-索引,避免两个分类下索引重复的冲突),每次选中/取消选中时重新计算总估值:
class CostCalculator { // 原始数据源 private sourceData: CostResponse // 存储选中项:值格式为 `${category}-${index}` private selectedSet = new Set<string>() // 当前总估值的最小/最大值 totalMin = 0 totalMax = 0 constructor(sourceData: CostResponse) { this.sourceData = sourceData } // 切换选中状态的核心方法 toggleSelect(category: ItemCategory, index: number): void { const key = `${category}-${index}` const item = this.sourceData[category][index] if (!item) return // 边界判断,防止非法索引报错 if (this.selectedSet.has(key)) { // 已有选中,执行取消:减去对应值 this.totalMin -= item.MinValue this.totalMax -= item.MaxValue this.selectedSet.delete(key) } else { // 未选中,执行勾选:加上对应值 this.totalMin += item.MinValue this.totalMax += item.MaxValue this.selectedSet.add(key) } } // 格式化输出页脚显示文本 getFooterText(): string { return `usd ${this.totalMin.toFixed(2)} - usd ${this.totalMax.toFixed(2)}` } // 可选:重置所有选中 reset(): void { this.selectedSet.clear() this.totalMin = 0 this.totalMax = 0 } }
3. 调用示例
// 你的接口返回数据 const mockData: CostResponse = { "DataNeeded":[ {"MinValue":0.00,"MaxValue":0.00}, {"MinValue":1.50,"MaxValue":3.00} ], "Resources":[ {"MinValue":5.00,"MaxValue":10.00}, {"MinValue":2.25,"MaxValue":4.75}, {"MinValue":0.00,"MaxValue":0.00} ] } // 初始化计算器 const calculator = new CostCalculator(mockData) // 模拟勾选DataNeeded第2条(索引1) calculator.toggleSelect('DataNeeded', 1) console.log(calculator.getFooterText()) // 输出 usd 1.50 - usd 3.00 // 模拟勾选Resources第1条(索引0) calculator.toggleSelect('Resources', 0) console.log(calculator.getFooterText()) // 输出 usd 6.50 - usd 13.00 // 模拟取消勾选DataNeeded第2条 calculator.toggleSelect('DataNeeded', 1) console.log(calculator.getFooterText()) // 输出 usd 5.00 - usd 10.00
4. 前端UI绑定提示
如果是搭配React/Vue等框架使用,把totalMin、totalMax改成响应式状态即可,复选框的change事件直接调用toggleSelect方法传入对应分类和索引就行,不需要额外处理计算逻辑。
内容的提问来源于stack exchange,提问作者Developer18
相关产品推荐
相关产品推荐

