Angular:如何在ngFor循环内仅调用一次processStatus函数并复用结果
Angular ngFor 避免重复调用函数的解决方案
你的写法无效是因为Angular的*ngFor语法不支持直接通过let声明调用函数赋值的变量,下面提供两种可行的实现方式:
方案一:模板内用*ngIf as缓存结果
利用*ngIf的as语法,既完成存在性判断,又将函数调用结果缓存到变量中,实现单次调用复用:
<ng-container *ngFor="let status of processCompStatusOrder; let i = index;"> <ng-container *ngIf="processStatus(status) as p"> <div> <clr-icon class="icon" [attr.shape]="svc.getIcon(p)"></clr-icon> {{ 'base.' + p?.toLowerCase() | i18next }} </div> </ng-container> </ng-container>
这里*ngIf="processStatus(status) as p"会执行一次函数调用,将结果存入p,同时只有当p存在时才渲染内部内容,完全替代原代码的判断逻辑,且避免了重复调用。
方案二:组件类预处理数据(性能更优)
将函数调用从模板移到组件类中,提前计算好所有结果,模板直接复用预处理后的数据,减少变更检测时的函数执行次数:
组件类代码
// 定义接口存储处理后的数据结构 interface ProcessedStatus { originalStatus: string; statusValue: string | undefined; } processedStatuses: ProcessedStatus[] = []; ngOnInit(): void { // 初始化时处理数据 this.updateProcessedStatuses(); } // 当依赖数据(process/processCompStatusOrder)变化时,重新处理 updateProcessedStatuses(): void { this.processedStatuses = this.processCompStatusOrder .map(status => ({ originalStatus: status, statusValue: this.processStatus(status) })) // 提前过滤掉无效结果,模板无需再判断 .filter(item => !!item.statusValue); } // 原processStatus方法保持不变 processStatus(status: string): string | undefined { return this.process?.[status]?.process?.status; }
模板代码
<ng-container *ngFor="let item of processedStatuses; let i = index;"> <div> <clr-icon class="icon" [attr.shape]="svc.getIcon(item.statusValue)"></clr-icon> {{ 'base.' + item.statusValue?.toLowerCase() | i18next }} </div> </ng-container>
这种方式更适合数据频繁变化或需要多处复用处理结果的场景,性能表现更好。
内容的提问来源于stack exchange,提问作者user7046311
相关产品推荐
相关产品推荐

