Angular中NgFor遍历请假数组统计各假型总时长及简化实现问题
实现方案
第一步:预处理数据(同时解决两个需求)
你原有月度请假数据为多对象数组结构,每次取值都需要循环遍历,我们可以在组件拿到原始数据后做一次预处理,转成更易用的结构,同时完成总时长统计:
// 组件中定义变量 processedLeaves: Record<string, Record<string, number>> = {}; totalCL = 0; totalWFH = 0; // 拿到原始leaves数据后执行该方法 processLeaveData() { Object.entries(this.leaves).forEach(([month, records]) => { // 初始化默认值,避免缺少对应类型时显示空值 const monthData: Record<string, number> = { CL: 0, WFH: 0 }; records.forEach(record => { const [type, hours] = Object.entries(record)[0]; monthData[type] = hours; // 累加对应类型的总时长 if (type === 'CL') this.totalCL += hours; if (type === 'WFH') this.totalWFH += hours; }); this.processedLeaves[month] = monthData; }); }
你给出的预期效果中3月CL为1,只需在原始数据的
Mar 2021数组中补充{"CL": 1}即可得到对应的统计结果。
第二步:修改HTML模板
预处理后的数据可以直接读取属性,无需调用自定义函数,页脚直接绑定统计好的总时长即可:
<table class="table table-statitics2 table-bordered" aria-label="Leave"> <thead> <tr> <th scope="col"></th> <th scope="col" class="casual"><strong>CL</strong></th> <th scope="col" class="earned"><strong>WFH</strong></th> </tr> </thead> <tbody *ngIf="processedLeaves"> <tr *ngFor="let item of processedLeaves | keyvalue : keepOriginalOrder"> <td class="date">{{item.key}}</td> <td>{{item.value.CL}}</td> <td>{{item.value.WFH}}</td> </tr> </tbody> <tfoot> <tr> <td><strong>Total</strong></td> <td><strong>{{totalCL}}</strong></td> <td><strong>{{totalWFH}}</strong></td> </tr> </tfoot> </table>
可选方案:不预处理数据的简化写法
如果不想改动原始数据结构,也可以直接在模板中用Array.find简化取值,无需自定义函数:
<td>{{item.value.find(i => i.hasOwnProperty('CL'))?.['CL'] || 0}}</td> <td>{{item.value.find(i => i.hasOwnProperty('WFH'))?.['WFH'] || 0}}</td>
这种方式无需修改ts代码,但每次渲染都要执行查找逻辑,数据量大的情况下性能不如预处理方案。
内容的提问来源于stack exchange,提问作者sadique mohammed
相关产品推荐
相关产品推荐

