Angular如何根据输入年龄过滤ngFor遍历的amountArray数组
实现步骤
1. 调整TS变量定义与监听逻辑
首先拆分原始金额数组和展示用的过滤数组,同时监听年龄、币种的变化动态触发过滤,还要注意将输入的年龄转为数字类型避免比较错误:
// 原始金额选项,固定不修改 public originalAmountArray = [ { value: 10000 }, { value: 15000 }, { value: 20000 }, { value: 25000 }, { value: 50000 } // 按需求补充欧元需要的50000选项 ]; // 模板渲染用的过滤后数组 public filteredAmountArray = [...this.originalAmountArray]; // 替换为你实际的币种变量,示例为非欧元默认值 public currencyType = 'CNY'; ngOnInit() { // 监听年龄输入变化,实时更新过滤选项 const birthDateControl = (this.formGroup.get('formArray') as FormArray).at(0).get('birthDate'); birthDateControl.valueChanges.subscribe(age => { this.filterAmountOptions(Number(age)); }); // 如果币种支持切换,可额外监听币种变化同步触发过滤 } // 核心过滤金额逻辑 filterAmountOptions(age: number) { // 年龄为空或非数字时默认返回全部选项 if (!age || isNaN(age)) { this.filteredAmountArray = [...this.originalAmountArray]; return; } if (age > 50) { if (this.currencyType === 'EUR') { // 欧元仅保留25000、50000 this.filteredAmountArray = this.originalAmountArray.filter(item => [25000, 50000].includes(item.value)); } else { // 非欧元仅保留10000、15000 this.filteredAmountArray = this.originalAmountArray.filter(item => [10000, 15000].includes(item.value)); } } else { // 50岁及以下展示全部选项,可根据实际需求调整规则 this.filteredAmountArray = [...this.originalAmountArray]; } } next() { this.personAge = Number((this.formGroup.get('formArray') as FormArray).at(0).get('birthDate').value); // 点击下一步主动触发一次过滤,避免漏判 this.filterAmountOptions(this.personAge); // 原有next逻辑保留 }
2. 修改HTML模板的遍历数据源
把原来遍历的amountArray替换为过滤后的filteredAmountArray即可:
<ng-container *ngFor="let a of filteredAmountArray"> <div class="amount-div"> <input type="radio" id="{{ a.value }}" formControlName="amount" value="{{ a.value }}" /> <label for="{{ a.value }}"> <span> {{ a.value }} </span> <span>{{ currencySymbol }}</span> </label> </div> </ng-container>
注意事项
- 你之前返回undefined大概率是因为没有做类型转换,输入的年龄是字符串直接参与比较导致逻辑异常,加
Number()转换即可解决 - 两步stepper场景下,建议在切换到第二步的钩子中也主动调用一次
filterAmountOptions,避免用户填完年龄直接下一步没有触发valueChanges的情况 - 若选择金额后用户修改年龄导致当前选中的金额不在过滤后的列表里,建议补充重置
amount表单控件的逻辑,避免残留无效值
内容的提问来源于stack exchange,提问作者user16352891
相关产品推荐
相关产品推荐

