获取NgFor项Angular的总数



我有一个包含不同休假类型的休假计数的休假数组,我必须返回所有休假类型的总数

array = {
"Jan 2021": [
{
"WFH": 17.5
},
{
"CL": 3.5
}
],
"Feb 2021": [
{
"WFH": 19.5
},
{
"CL": 2.5
}
],
"Mar 2021": [
{
"WFH": 13
}
]
}
这是我的html文件:
<table class="table table-statitics2 table-bordered" aria-label="Leave">
<thead>
<tr>
<th scope="col"></th>
<th scope="col" class="casual">CL</th>
<th scope="col" class="earned">EL</th>
</tr>
</thead>
<tbody *ngIf="leaves">
<tr *ngFor="let item of leaves | keyvalue : keepOriginalOrder">
<td class="date">{{item.key}}</td>
<td>{{getMonthyItem(item.value, "CL")}}</td>
<td>{{getMonthyItem(item.value, "EL")}}</td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="2" class="text-center text-danger" scope="row">Total</th>
<th scope="row">Total of CL</th>
<th scope="row">Total of EL</th>
</tr>
</tfoot>
</table>

这是我的函数返回休假数

getMonthyItem(items, object)
{
let result = '';
items.forEach(element => {
if(Object.keys(element) == object)
{
result  = element[object];
}
});
return result;
}

我怎么能返回表的页脚部分的每个休假类型的总数,也有任何简单的方法返回休假计数直接在html页面上没有函数,已经使用。

预期结果为,

<表类>CL亲密tbody><<tr>2021年1月3.517.52021年2月2.519.52021年3月113总数750
<table class="table table-statitics2 table-bordered" aria-label="Leave">
<thead>
<tr>
<th scope="col"></th>
<th scope="col" class="casual">CL</th>
<th scope="col" class="earned">EL</th>
</tr>
</thead>
<tbody *ngIf="leaves">
<tr *ngFor="let item of leaves | keyvalue : keepOriginalOrder">
<td class="date">{{item.key}}</td>
<td>{{getMonthyItem(item.value, "CL")}}</td>
<td>{{getMonthyItem(item.value, "EL")}}</td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="2" class="text-center text-danger" scope="row">Total</th>
<th scope="row">Total of CL</th>
<th scope="row">Total of EL</th>
</tr>
<tr> 
<td>total('CL')</td>
<td>total('EL')</td>
</tr>
</tfoot>
</table>

,然后在.ts函数中定义一个新函数。正如我看到的,您已经保留了包含所有信息的leaves字段。所以应该是

public total (type: string): number {
let sum = 0;
Object.keys(this.leaves).forEach(key => {
this.leaves[key].forEach(element => {
sum = sum + (element[type] ? element[type] : 0);
});
});
return sum;
}

我要做的是在一个函数中计算总数,并手动添加一个额外的行与数据:

HTML:

<table class="table table-statitics2 table-bordered" aria-label="Leave">
<thead>
<tr>
<th scope="col"></th>
<th scope="col" class="casual">CL</th>
<th scope="col" class="earned">EL</th>
</tr>
</thead>
<tbody *ngIf="leaves">
<tr *ngFor="let item of leaves | keyvalue : keepOriginalOrder">
<td class="date">{{item.key}}</td>
<td>{{getMonthyItem(item.value, "CL")}}</td>
<td>{{getMonthyItem(item.value, "EL")}}</td>
</tr>
<tr>
<td class="date">Total</td>
<td>{{total(leaves, "CL")}}</td>
<td>{{total(leaves, "WFH")}}</td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="2" class="text-center text-danger" scope="row">Total</th>
<th scope="row">Total of CL</th>
<th scope="row">Total of EL</th>
</tr>
</tfoot>
</table>

功能:

total(items, object)
{
let result = 0;
items.forEach(x => {
if(Object.keys(x) == object)
{
result  = result + x[object];
}
});
return result;
}

最新更新