问题描述
我已经简化了这个,但假设我的数据库中有一个表 Persons 并且我已经从表中获取了所有记录。如何在 Angular 表中仅显示具有正确行号的就业人员。
我也知道在这种情况下我只能直接从数据库中获取就业人员,但正如我所说,这只是我需要的东西的示例
来自数据库的表人
Person | employed
Mike no
Angela yes
Josh yes
Tim no
Michelle yes
我需要这个结果:因为我不是真的想要索引值,我想要表行号
RowNum | Person
1 Angela
2 Josh
3 Michelle
我得到的结果
RowNum | Person
2 Angela
3 Josh
5 Michelle
这是代码:
<table>
<thead>
<th>RowNum</th>
<th>Person</th>
</thead>
<tbody>
<tr *ngFor="let item of persons; let i = index;">
<ng-container *ngIf="item.employed == 'yes'">
<td>{{i + 1}}</td>
<td>{{item.Person}}</td>
</ng-container>
</tr>
</tbody>
</table>
我知道为什么会发生这种情况,所以我尝试了几个版本的手动递增计数器,但没有运气...我没想到这是我会遇到的问题...
解决方法
为什么不先过滤,然后再遍历数组?
我是说
let employedPersons = persons.filter(e => e.employed == 'yes');
<tr *ngFor="let item of employedPersons; let i = index;">
<td>{{i + 1}}</td>
<td>{{item.Person}}</td>
</tr>
,
创建原始数组对象的副本,并为其添加 rowNum 属性,并为就业和失业人员添加不同的行号,这样您就可以为员工而不是员工获得不同的行值
let employedCounter = 0;
let unemployedCounter = 0;
this.modifiedPersons = this.persons.map(person => {
if (person.employed == 'yes') {
employedCounter = employedCounter + 1;
return { ...person,rowNum: employeedCounter };
} else {
unemployedCounter = unemployedCounter + 1;
return { ...person,rowNum: unemployeedCounter };
}
});
并用 modifiedPersons 替换您的人员
<tr *ngFor="let item of modifiedPersons; let i = index;">
<ng-container *ngIf="item.employed">
<td>{{ item.rowNum }}</td>
<td>{{ item.person }}</td>
</ng-container>
</tr>