angular - 模板内嵌套循环的角度索引
问题描述
我在表中有一个嵌套循环,但我只想在 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)。
解决方案
有多种选择如何处理这个:
服务器预处理 修剪服务器上的数据并发送到客户端,只设置您想要呈现的设置。优点是客户端的浏览器不必处理大量数据(并下载它们)。或者在每个用户上引入一个“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
推荐阅读
- reactjs - JSDoc 在使用 webpack 开发服务器的 Lerna monorepo 项目中的本地包中不起作用,但在发布到包注册表时起作用
- apache - 为每个页面重写 url 中的 get 参数
- python - 有没有办法在浏览器中预览 pdf/image 文件?
- reactjs - 使用 props 覆盖 React 组件的基本样式
- linux - Cassandra-i 能够通过 sudo 命令连接但无法通过 cqlsh 连接
- vb.net - Vb.net,实例化一个类
- android - 如何修复:无法启动服务 Intent - RNPushNotificationRegistrationService
- php - 尝试在使用回声行时将发送者和接收者与内部联合表分开
- php - SQLSTATE [HY093]:无效参数编号错误,即使我使用的是 bindParam 而不是执行
- jakarta-ee - TimerService#createTimer 忽略延迟