【问题标题】:How to get correct ngfor index/row number value based on condition如何根据条件获取正确的 ngfor 索引/行号值
【发布时间】:2021-07-13 12:25:01
【问题描述】:

我对此进行了过度简化,但假设我的数据库中有一个 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>

我知道为什么会这样,所以我尝试了几个版本的手动递增计数器但没有运气...我没想到这是我会遇到问题的事情...

【问题讨论】:

  • 它的发生是因为:index: number: iterable 中当前项的索引。
  • 嗨,我知道,我需要的行号不完全是索引值
  • NgForOf 仅提供 8 个导出的值,这些值可以别名为局部变量。 https://angular.io/api/common/NgForOf#local-variables displayIndex 不是其中之一。

标签: angular conditional-statements ngfor angular-ng-if row-number


【解决方案1】:

为什么不先过滤,然后再遍历数组?

我是说

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>

【讨论】:

  • 嗨,因为在真正的问题中,我有一个对象,其中包含对象列表,以及这些对象内部的另一个对象列表......所以我实际上必须在其中显示三个不同的表来自 1 个对象的前端
  • 这是最准确的方法。
【解决方案2】:

创建原始数组对象的副本,并为其添加 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-11
    • 2021-10-12
    • 1970-01-01
    • 2018-04-29
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多