Angular 11 fa-icon动态绑定[icon]属性时函数频繁调用问题排查
问题原因
该现象是Angular默认变更检测机制的正常表现:
- Angular每次运行变更检测周期时,都会重新执行模板中绑定的所有函数、表达式,校验返回值是否变化,判断是否需要更新视图
- 所有前端交互(点击、输入、鼠标移动等)、异步事件(HTTP响应、定时器回调、Promise回调等)都会触发变更检测,每一轮变更检测都会遍历所有模板绑定的逻辑执行
- 你当前的写法下,列表有多少项,每一轮变更检测就会调用多少次
getIcon,变更检测触发越频繁,总调用次数就越高,远超出列表数量是正常情况。
优化方案
方案1:预计算图标属性
在获取到listOfPets数据时就提前把每一项对应的图标值计算好,挂载到pet对象的属性上,模板直接绑定属性即可,无需函数调用。
代码示例:
// 拿到列表数据后统一预计算 this.listOfPets = this.listOfPets.map(pet => ({ ...pet, icon: this[pet.type] }))
模板调整为:
<li class="pet-list__entry" *ngFor="let pet of listOfPets"> <div class="pet-list__entry__image-segment"> <fa-icon [icon]="pet.icon"></fa-icon> </div> <div class="pet-list__entry__data-segment"> {{ pet.name }} </div> </li>
方案2:使用纯管道
Angular的纯管道仅在输入参数发生值变更(基础类型)或引用变更(引用类型)时才会重新执行,不会每次变更检测都运行。
先定义纯管道:
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'petIcon', pure: true }) export class PetIconPipe implements PipeTransform { transform(petType: string, component: any): string { return component[petType]; } }
模板使用:
<fa-icon [icon]="pet.type | petIcon: this"></fa-icon>
方案3:调整组件变更检测策略为OnPush
给组件配置OnPush变更检测策略后,仅当组件输入属性变更、组件内部触发交互事件、或手动触发变更检测时,才会运行当前组件的变更检测,大幅降低执行频率。
代码示例:
import { ChangeDetectionStrategy, Component } from '@angular/core'; @Component({ selector: 'app-pet-list', templateUrl: './pet-list.component.html', changeDetection: ChangeDetectionStrategy.OnPush }) export class PetListComponent { // 原有组件逻辑不变 }
内容的提问来源于stack exchange,提问作者Phil
相关产品推荐
相关产品推荐

