首页 > 解决方案 > 模板内嵌套循环的角度索引

问题描述

我在表中有一个嵌套循环,但我只想在 DOM 中显示有限数量的行,并在单击按钮时加载更多行。

循环看起来像这样:

<ng-container *ngFor="let organisation of organisations; let organisationIndex = index;">
    <ng-container *ngFor="let department of organisation.departments; let departmentIndex = index;">
        <ng-container *ngFor="let user of department.users; let userIndex = index;">
            <div>
                This is a List entry and i only want this 20 times in total (not for each loop)
            </div>
        </ng-container>
    </ng-container>
</ng-container>

如果可能的话,在不增加复杂性的情况下,在嵌套循环中获取索引的最平滑方法是什么?

我不想用 css :nth-of-type 或类似的东西来做,因为我的数据集很大,即使元素被 css 隐藏,dom 也会变慢。

每个数组的长度是动态的,这使我无法制作静态公式(如 organizationIndex * 50)。

标签: angularngforangular-templatearray-indexing

解决方案


有多种选择如何处理这个:

服务器预处理 修剪服务器上的数据并发送到客户端,只设置您想要呈现的设置。优点是客户端的浏览器不必处理大量数据(并下载它们)。或者在每个用户上引入一个“totalIndex”,它在组织中是增量的和连续的。

角度修剪 - 子集合中的项目数量相等

如果您的子集合中的项目包含相同数量的项目。您必须将索引相乘并检查您是否已经输出了 20 行。如果是这样*ngIf,请避免显示更多。使用*ngIf项目时根本不渲染。

<ng-container *ngFor="let organisation of organisations; let organisationIndex = index;">
    <ng-container *ngFor="let department of organisation.departments; let departmentIndex = index;">
        <ng-container *ngFor="let user of department.users; let userIndex = index;">
            <div *ngIf="(organisationIndex * organisation.departments.length) + (departmentIndex * department.users.length) + userIndex < 20">
                This is a List entry and i only want this 20 times
            </div>
        </ng-container>
    </ng-container>
</ng-container>

Angular trimming - counterpipe 如果子集合中的项目数量不相等,请使用counterpipe

import { Pipe, PipeTransform } from '@angular/core';
import { Counter } from './counter';

const counters = new WeakMap<any, Counter>();

@Pipe({
  name: 'counterPipe'
})
export class CounterPipe implements PipeTransform  {
  transform(value: any): Counter {
    if (!counters.has(value)) {
      counters.set(value, new Counter());
    }
    return counters.get(value);
  }
}

这将在处理实体时添加计数器,*ngFor因此您始终知道要渲染的元素数量。

用这个管道包装你的代码:

<ng-container *ngFor="let counter of [organisations | counterPipe]">
  <ng-container *ngFor="let organisation of organisations; let organisationIndex = index;">
      <ng-container *ngFor="let department of organisation.departments; let departmentIndex = index;">
          <ng-container *ngFor="let user of department.users; let userIndex = index;">
              <div *ngIf="counter.inc() < 20">
                This is a List entry and i only want this 20 times
              </div>
          </ng-container>
      </ng-container>
  </ng-container>
</ng-container>

使用示例可见https://stackblitz.com/edit/angular-nested-ngfor-ydvxjv


推荐阅读