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

Angular二级联动下拉框实现遇undefined错误求助

问题分析

  1. 变量逻辑混乱:

    • assetDS未赋值,原始数据源无存储载体,导致find方法无法获取数据
    • assetObj被错误赋值为选中的ID(数字类型),后续HTML循环时直接触发undefined错误
    • 第二个下拉框未单独存储过滤后的tranType数据,复用第一个下拉的数据源导致逻辑冲突
  2. 数据结构匹配错误:

    • 数据源中tranType是字符串类型(如"MAINTENANCE"),但代码错误尝试访问x.tranType.assetID,直接抛出undefined
    • HTML中第二个下拉框绑定items.tranType.assetID、显示items.tranType.tranType,完全不符合实际数据结构
  3. 初始化缺失:

    • 关键变量未初始化,组件加载时因undefined触发报错

修复方案

1. 调整TS代码

修正变量定义,初始化数据并重构联动逻辑:

// 存储原始数据源
assetDS: any[] = [];
// 第一个下拉框的去重资产状态选项
assetConditionOptions: any[] = [];
// 第二个下拉框的过滤后tranType数据
filteredTranTypes: string[] = [];

ngOnInit(): void {
  // 调用接口获取原始数据(或直接赋值测试数据)
  this.serviceSVC.getAssetCondition(5,10).subscribe((res: any[]) => {
    this.assetDS = res;
    // 提取去重的资产状态类型作为第一个下拉选项
    const uniqueConditions = new Map();
    res.forEach(item => {
      const condition = item.assetConditionType;
      if (!uniqueConditions.has(condition.id)) {
        uniqueConditions.set(condition.id, condition);
      }
    });
    this.assetConditionOptions = Array.from(uniqueConditions.values());
  });
}

selectedType(trigger: MatSelectChange) {
  // 获取选中的资产状态类型对象
  const selectedCondition = this.assetConditionOptions.find(opt => opt.id === trigger.value);
  if (selectedCondition) {
    // 根据选中状态过滤对应tranType
    this.filteredTranTypes = this.assetDS
      .filter(item => item.assetConditionType.assetConditionType === selectedCondition.assetConditionType)
      .map(item => item.tranType);
    // 可选:默认选中第一个tranType
    if (this.filteredTranTypes.length > 0) {
      this.serviceLogArray.get('tranType')?.patchValue(this.filteredTranTypes[0]);
    }
  }
}

2. 修正HTML代码

调整下拉框的数据源绑定、值绑定和显示内容:

<td>
  <mat-select formControlName="assetCondition" style="width:200px;padding:10px"
             (selectionChange)="selectedType($event)">
      <mat-option *ngFor="let condition of assetConditionOptions" [value]="condition.id">
          {{condition.assetConditionType}} <!-- 显示SERVICEABLE/UNSERVICEABLE -->
      </mat-option>
  </mat-select>
</td>
<td>
  <mat-select formControlName="tranType" style="width:200px;padding:10px">
       <mat-option *ngFor="let type of filteredTranTypes" [value]="type">
         {{type}} <!-- 显示MAINTENANCE/DISPOSAL等 -->
      </mat-option>
  </mat-select>
</td>

关键修改说明

  • 拆分数据源:用assetDS存原始数据,assetConditionOptions存第一个下拉的去重选项,filteredTranTypes存第二个下拉的过滤后数据,避免变量复用混乱
  • 修正数据访问逻辑:根据实际数据源结构,用item.assetConditionType.assetConditionType匹配状态,直接提取item.tranType作为第二个下拉选项
  • 增加初始化:在ngOnInit中处理接口返回数据,生成第一个下拉的选项,避免组件加载时的undefined错误
  • 优化显示内容:第一个下拉显示状态名称而非ID,更贴合业务需求

内容的提问来源于stack exchange,提问作者Alluring

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:25:27