You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用FormArray与FormGroups无法获取下拉选中值,级联下拉实现遇阻

解决动态表格级联下拉问题

核心问题分析

你当前的代码无法获取行内州ID,是因为items是FormArray,直接调用get('state')无法定位到对应索引行的控件,导致value为undefined,转成数字后返回NaN。

修复步骤

1. 正确获取当前行的州ID

修改onStateChange方法,通过索引定位到FormArray中对应的FormGroup,再获取state控件的值:

onStateChange(index: number) {
  // 获取对应索引的行表单组
  const itemForm = this.mlbForm.get('items')?.at(index) as FormGroup;
  const stateID = Number(itemForm.get('state')?.value);

  if (!isNaN(stateID)) {
    // 根据stateID获取对应城市列表(替换成你的数据获取逻辑)
    const targetCities = this.cityList.filter(city => city.stateId === stateID);
    // 更新当前行的城市选项,同时重置城市、球队的选中值
    itemForm.get('city')?.setValue(null);
    itemForm.get('team')?.setValue(null);
    this.rowCities[index] = targetCities;
  }
}

2. 维护每行的城市选项数组

在组件类中定义数组存储每行的城市选项,与FormArray同步更新:

// 存储每行的城市选项
rowCities: any[][] = [];

// 添加行时同步初始化城市选项数组
addRow() {
  const newRow = this.fb.group({
    state: [null],
    city: [null],
    team: [null]
  });
  (this.mlbForm.get('items') as FormArray).push(newRow);
  this.rowCities.push([]);
}

// 删除行时同步移除对应城市选项
deleteRow(index: number) {
  (this.mlbForm.get('items') as FormArray).removeAt(index);
  this.rowCities.splice(index, 1);
}

3. 模板中绑定当前行的城市选项

将城市下拉的选项绑定到rowCities[index]:

<select formControlName="city" (change)="onCityChange(index)">
  <option [value]="null">选择城市</option>
  <option *ngFor="let city of rowCities[index]" [value]="city.id">
    {{city.name}}
  </option>
</select>

4. 球队级联逻辑(类似实现)

参考州→城市的逻辑,定义rowTeams数组,在onCityChange方法中获取当前行的城市ID,加载对应球队列表并更新rowTeams[index],最后在模板中绑定球队下拉选项。

内容的提问来源于stack exchange,提问作者Brandon Michael Hunter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 02:34:52