Angular中如何根据ngFor的索引值将组件添加到不同div容器?
实现方案
不需要对products数组做二维分组转换,全程可以靠Angular原生特性在模板层完成逻辑,两种写法适配不同场景:
首先需要修正原代码的结构错误:原来的全量循环块写在了.row容器的外部,渲染出的商品卡片不会归属于内部的三个grid列,需要删掉这部分独立的循环逻辑,把卡片渲染移到对应列的容器内部。
零代码快速实现(适合新手)
直接在三个固定grid列的内部,用Angular内置结构指令完成索引匹配判断,不需要改动组件类的任何代码,也不需要修改原商品数组结构:
<div class="row"> <!--Grid column: 存放i%3 == 0的商品--> <div id="gridColumn1" class="col-lg-4 col-md-12 mb-4"> <ng-container *ngFor="let product of products | async; index as i"> <app-product-card *ngIf="i % 3 === 0" [product]="product"></app-product-card> </ng-container> </div> <!--Grid column: 存放i%3 == 1的商品--> <div id="gridColumn2" class="col-lg-4 col-md-6 mb-4"> <ng-container *ngFor="let product of products | async; index as i"> <app-product-card *ngIf="i % 3 === 1" [product]="product"></app-product-card> </ng-container> </div> <!--Grid column: 存放i%3 == 2的商品--> <div id="gridColumn3" class="col-lg-4 col-md-6 mb-4"> <ng-container *ngFor="let product of products | async; index as i"> <app-product-card *ngIf="i % 3 === 2" [product]="product"></app-product-card> </ng-container> </div> </div>
实现说明:
- 用到的都是Angular最基础的内置能力:
*ngFor获取循环的原生索引、*ngIf做条件渲染、ng-container做无额外DOM渲染的逻辑包裹 - 注意不要在同一个元素上同时挂载
*ngFor和*ngIf,Angular不支持同元素绑定多个结构指令,必须用ng-container做隔离 - 这种写法会对全量商品数组遍历3次做条件判断,对于几十到几百个商品的常规业务场景完全无性能感知
性能优化实现
如果商品量较大,担心多次遍历的性能损耗,可以写一个轻量的Angular自定义管道,专门做索引余数过滤,依然不需要修改原商品数组的结构:
- 编写管道逻辑
// mod-index.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'modIndex' }) export class ModIndexPipe implements PipeTransform { transform<T>(sourceList: T[], targetRemainder: number): T[] { // 仅返回索引对3取余等于目标值的元素 return sourceList.filter((item, index) => index % 3 === targetRemainder); } }
- 在对应业务模块的
declarations数组中声明这个管道 - 模板层简化逻辑,直接通过管道做过滤,不再需要手动写条件判断:
<div class="row"> <div id="gridColumn1" class="col-lg-4 col-md-12 mb-4"> <app-product-card *ngFor="let product of (products | async | modIndex:0)" [product]="product"> </app-product-card> </div> <div id="gridColumn2" class="col-lg-4 col-md-6 mb-4"> <app-product-card *ngFor="let product of (products | async | modIndex:1)" [product]="product"> </app-product-card> </div> <div id="gridColumn3" class="col-lg-4 col-md-6 mb-4"> <app-product-card *ngFor="let product of (products | async | modIndex:2)" [product]="product"> </app-product-card> </div> </div>
实现说明:
- 管道是Angular原生的逻辑复用单元,纯函数的转换逻辑可以配合Angular的变更检测做缓存优化,性能优于模板内多次遍历判断的写法
- 全程没有改动
products的原始数组结构,不需要写二维分组的转换代码
内容的提问来源于stack exchange,提问作者Furkan Işıtan
相关产品推荐
相关产品推荐

