Angular 6中如何通过ngFor按Serie分组展示成分分析表格列表
Angular 6: Grouping Alloy Composition Data by Serie to Display Per-Serie Tables
嘿,这问题我熟!你现在的代码之所以每个数据项都生成单独表格,是因为直接循环了原始的扁平数据数组,没做分组处理。咱们分两步来搞定:先在组件里把数据按serie分组,再修改模板渲染分组后的内容。
第一步:在组件中对数据进行分组处理
首先在你的组件类里,用数组的reduce方法把原始数据按合金系列(serie)分组,生成一个以系列名为键、对应成分数组为值的对象:
import { Component, OnInit } from '@angular/core'; import { Certificate } from './certificate'; import { CERTIFICATES } from './your-data-path'; // 替换成你的数据源实际路径 @Component({ selector: 'app-alloy-certificates', templateUrl: './alloy-certificates.component.html' }) export class AlloyCertificatesComponent implements OnInit { originalCertificates = CERTIFICATES; groupedBySerie: { [serieName: string]: Certificate[] } = {}; ngOnInit(): void { // 执行分组逻辑 this.groupedBySerie = this.originalCertificates.reduce((groupedData, currentCert) => { const serie = currentCert.serie; // 如果当前系列还没在分组对象里,先初始化一个空数组 if (!groupedData[serie]) { groupedData[serie] = []; } // 将当前数据项加入对应系列的数组 groupedData[serie].push(currentCert); return groupedData; }, {} as { [serieName: string]: Certificate[] }); } }
第二步:修改HTML模板渲染分组后的表格
接下来修改模板,用Angular的keyvalue管道遍历分组后的对象(因为对象不能直接用*ngFor循环,keyvalue会把它转成键值对数组),每个系列对应一个独立表格:
<div class="cert-result"> <!-- 遍历每个合金系列分组 --> <div *ngFor="let serieEntry of groupedBySerie | keyvalue"> <!-- 显示系列名称 --> <h3>Serie: {{ serieEntry.key }}</h3> <!-- 该系列的成分表格 --> <table class="alloy-table"> <thead> <tr> <th>Element</th> <th>Composition</th> </tr> </thead> <tbody> <!-- 遍历当前系列下的所有成分数据 --> <tr *ngFor="let certificate of serieEntry.value"> <td>{{ certificate.ident }}</td> <td>{{ certificate.moy_certified }}</td> </tr> </tbody> </table> <!-- 可选:添加分隔线区分不同表格 --> <hr class="table-divider"> </div> </div>
额外优化(可选)
如果想要让表格样式更美观,可以加一点CSS:
.alloy-table { border-collapse: collapse; width: 300px; margin: 10px 0; } .alloy-table th, .alloy-table td { border: 1px solid #ddd; padding: 8px; text-align: left; } .alloy-table th { background-color: #f2f2f2; } .table-divider { border: none; border-top: 1px solid #ccc; margin: 20px 0; }
这样就能实现你想要的效果:每个合金系列对应一个单独的表格,里面展示该系列所有元素的成分数据啦!
内容的提问来源于stack exchange,提问作者Jim P.
相关产品推荐
相关产品推荐

