Angular中如何取出template_A内的col属性值并在表格中正常展示
问题原因
你当前代码中使用singleAssignment.template_A[0]的写法是将template_A作为数组取下标,但根据你提供的接口返回数据结构,template_A是普通对象类型,不存在数组下标对应的属性,因此会出现显示异常的问题。
解决方案
方案1:固定读取col_1、col_2字段
如果你明确需要读取的就是template_A下的col_1和col_2两个固定字段,直接修改模板的属性绑定逻辑即可,同时添加可选链操作符?.避免数据未加载完成时抛出undefined错误:
<table> <tr> <td>{{ singleAssignment.template }}</td> <td>{{ singleAssignment.template_A?.col_1 }}</td> <td>{{ singleAssignment.template_A?.col_2 }}</td> </tr> </table>
方案2:动态遍历template_A所有字段
如果template_A下的字段不固定,需要自动遍历所有字段渲染,可以搭配Angular内置的keyvalue管道实现动态遍历:
<table> <tr> <td>{{ singleAssignment.template }}</td> <td *ngFor="let item of singleAssignment.template_A | keyvalue"> {{ item.value }} </td> </tr> </table>
内容的提问来源于stack exchange,提问作者Anuj Todankar
相关产品推荐
相关产品推荐

