Angular中如何用嵌套循环实现按国家分组的HTML表格展示?
按国家分组展示数据的表格实现问题
期望输出
<th>COUNTRY:</th> BELGIUM <th>LABEL:</th> | <th>ISINCODE: </th> AB INBEV | NO0010571698 FRENCH <th>LABEL:</th> | <th>ISINCODE: </th> WWI | AO0010571614
当前错误输出
<th>COUNTRY:</th> BELGIUM FRENCH <th>LABEL:</th> | <th>ISINCODE: </th> AB INBEV | NO0010571698 <th>LABEL:</th> | <th>ISINCODE: </th> WWI | AO0010571614
数据结构
REGROUPEMENT = [ { TYPEVALUE: 11, ASSETCATLABEL: 'Actions individuelles', CURRENCY: 'EUR', AMOUNT: 1646956.5, PERCENTAGE: 79.22, ELEMENT: [ { LABEL: 'AB INBEV', PAYS_LIB: 'BELGIUM', ISINCODE: 'NO0010571698', }, { LABEL: 'WWI', PAYS_LIB: 'FRENCH', ISINCODE: 'AO0010571614', }, ], }, ];
当前Angular代码
<div class="container text-center "> <h2 class="pt-3 pb-3">HTML Table</h2> <table *ngFor="let item of REGROUPEMENT"> <tr> <th>TYPE</th> <th>PRICE</th> </tr> <tr > <td>{{ item.ASSETCATLABEL }}</td> <td>{{ item.AMOUNT }}</td> </tr> <tr> <th colspan="3">COUNTRY</th> </tr> <tr *ngFor="let elem of item.ELEMENT"> <td colspan="3"> {{ elem.PAYS_LIB }} </td> </tr> <tr> <th>LABEL</th> <th>ISINCODE</th> </tr> <tr *ngFor="let elem of item.ELEMENT"> <td> {{ elem.LABEL}}</td> <td> {{ elem.ISINCODE}}</td> </tr> </table> </div>
修改方案
第一步:在组件中处理数据分组
先把ELEMENT数组按PAYS_LIB字段分组,方便模板循环展示。在组件类中添加以下代码:
import { OnInit } from '@angular/core'; // ... 其他组件代码 groupedCountries: { country: string, elements: any[] }[] = []; ngOnInit() { // 创建分组映射 const countryGroups: { [key: string]: any[] } = {}; this.REGROUPEMENT.forEach(item => { item.ELEMENT.forEach(elem => { // 初始化当前国家的数组(如果不存在) if (!countryGroups[elem.PAYS_LIB]) { countryGroups[elem.PAYS_LIB] = []; } // 将元素加入对应国家的数组 countryGroups[elem.PAYS_LIB].push(elem); }); }); // 转换为数组格式,方便模板遍历 this.groupedCountries = Object.entries(countryGroups).map(([country, elements]) => ({ country, elements })); }
第二步:修改模板代码
替换原有的国家和元素循环部分,改为遍历分组后的数据:
<div class="container text-center "> <h2 class="pt-3 pb-3">HTML Table</h2> <table *ngFor="let item of REGROUPEMENT"> <tr> <th>TYPE</th> <th>PRICE</th> </tr> <tr > <td>{{ item.ASSETCATLABEL }}</td> <td>{{ item.AMOUNT }}</td> </tr> <!-- 遍历分组后的国家数据 --> <ng-container *ngFor="let group of groupedCountries"> <!-- 国家标题行 --> <tr> <th colspan="2">COUNTRY: {{ group.country }}</th> </tr> <!-- 元素表头行 --> <tr> <th>LABEL</th> <th>ISINCODE</th> </tr> <!-- 当前国家下的所有元素行 --> <tr *ngFor="let elem of group.elements"> <td> {{ elem.LABEL}}</td> <td> {{ elem.ISINCODE}}</td> </tr> </ng-container> </table> </div>
这样就能实现每个国家单独显示,下方紧跟对应元素的表格结构,符合期望输出。
内容的提问来源于stack exchange,提问作者amelabamelab440
相关产品推荐
相关产品推荐

