Angular二级联动下拉框实现遇undefined错误求助
问题分析
变量逻辑混乱:
assetDS未赋值,原始数据源无存储载体,导致find方法无法获取数据assetObj被错误赋值为选中的ID(数字类型),后续HTML循环时直接触发undefined错误- 第二个下拉框未单独存储过滤后的
tranType数据,复用第一个下拉的数据源导致逻辑冲突
数据结构匹配错误:
- 数据源中
tranType是字符串类型(如"MAINTENANCE"),但代码错误尝试访问x.tranType.assetID,直接抛出undefined - HTML中第二个下拉框绑定
items.tranType.assetID、显示items.tranType.tranType,完全不符合实际数据结构
- 数据源中
初始化缺失:
- 关键变量未初始化,组件加载时因
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
相关产品推荐
相关产品推荐

