Angular中无法显示对象数组嵌套REF值问题求助
问题排查与解决方案
核心错误分析
- 数据源错误:
MET是数组类型,直接访问MET.RESOLUTION会返回undefined——只有数组内的每个对象才拥有RESOLUTION属性。 - 插值表达式错误:即使数据源正确,循环变量
l已经是RESOLUTION数组中的单个对象(结构为{ REF: "01" }),无需通过嵌套路径访问REF,直接调用l.REF即可。
修正后的模板代码
根据场景提供两种通用修正方案:
方案1:适配MET数组多元素场景
如果MET可能包含多个对象,为每个对象单独渲染对应的RESOLUTION数据:
<div class="container text-center" *ngIf="MET"> <h2 class="pt-3 pb-3">HTML Table</h2> <table class="mb-5"> <tr> <th>Isin</th> <th>Denomination</th> </tr> <tr *ngFor="let line of MET"> <td>{{ line.ISINCODE }}</td> <td>{{ line.LABEL }}</td> </tr> </table> <br /> <table class="mb-5"> <tr> <th>Code</th> </tr> <!-- 先遍历MET数组的每个元素 --> <ng-container *ngFor="let line of MET"> <!-- 再遍历当前元素的RESOLUTION数组 --> <tr *ngFor="let res of line.RESOLUTION"> <td>{{ res.REF }}</td> </tr> </ng-container> </table> </div>
方案2:适配MET数组仅单个元素场景
如果确定MET只会有一个对象,可直接访问数组第一个元素的RESOLUTION:
<div class="container text-center" *ngIf="MET"> <h2 class="pt-3 pb-3">HTML Table</h2> <table class="mb-5"> <tr> <th>Isin</th> <th>Denomination</th> </tr> <tr *ngFor="let line of MET"> <td>{{ line.ISINCODE }}</td> <td>{{ line.LABEL }}</td> </tr> </table> <br /> <table class="mb-5"> <tr> <th>Code</th> </tr> <tr *ngFor="let res of MET[0].RESOLUTION"> <td>{{ res.REF }}</td> </tr> </table> </div>
效果验证
修正后模板会正确遍历RESOLUTION数组,渲染出REF的值(示例中为01)。
内容的提问来源于stack exchange,提问作者pops1348
相关产品推荐
相关产品推荐

