Angular 10使用*ngFor循环在表格中展示嵌套JSON对象数据不显示问题
问题根因
- 数组赋值逻辑错误:
Object.assign用于对象属性合并,你要覆盖数组直接赋值即可,原有写法无法触发Angular的变更检测刷新视图 - 嵌套结构访问错误:
attItems.ProductAttributeItems是数组类型,你直接当成对象访问.MasterProductAttributeItem自然拿不到值 - 可选链漏加:第三列的
ProductAttributeItems访问没有加可选链,数据未加载完成时会抛出控制台报错,阻塞渲染
TypeScript 代码修正
productAttributeItems: any[] = []; getProductAttributeItems() { this.productAttributeItems = this.productAttributeItems.filter(b => b.ProductId == 5); this.productService.getProductAttributesItems(5).subscribe(x => { // 直接赋值替换数组,触发变更检测 this.productAttributeItems = x; console.log(x); }); }
HTML 代码修正
根据业务需求二选一即可:
方案1:每个主条目只展示第一个嵌套属性
<table class="table table-hover"> <thead> <tr> <th>Attribute Name</th> <th>Name</th> <th>Price</th> </tr> </thead> <tbody> <tr *ngFor="let attItems of productAttributeItems"> <td>{{ attItems.Name }}</td> <td>{{ attItems.ProductAttributeItems?.[0]?.MasterProductAttributeItem?.Name }}</td> <td style="width: 40%; white-space: nowrap">{{ attItems.ProductAttributeItems?.[0]?.PriceAdjustment }}</td> </tr> </tbody> </table>
方案2:展示主条目下所有嵌套属性,用嵌套循环
<table class="table table-hover"> <thead> <tr> <th>Attribute Name</th> <th>Name</th> <th>Price</th> </tr> </thead> <tbody> <ng-container *ngFor="let attItems of productAttributeItems"> <tr *ngFor="let subItem of attItems.ProductAttributeItems || []"> <td>{{ attItems.Name }}</td> <td>{{ subItem.MasterProductAttributeItem?.Name }}</td> <td style="width: 40%; white-space: nowrap">{{ subItem.PriceAdjustment }}</td> </tr> </ng-container> </tbody> </table>
内容的提问来源于stack exchange,提问作者Pirlo
相关产品推荐
相关产品推荐

