有多种选择如何处理这个:
服务器预处理
修剪服务器上的数据并发送到客户端,只设置您想要呈现的设置。优点是客户端的浏览器不必处理大量数据(并下载它们)。或者在每个用户上引入一个“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