如何解决Angular模板绑定调用isSelected触发no-call-expression lint错误
@angular-eslint/template/no-call-expression 规则禁止在模板绑定中直接调用方法,核心是为了避免变更检测频繁触发方法执行导致性能损耗,针对你的场景有两种可行方案:
方案1:使用纯管道(推荐)
该方案完全符合lint规则,同时保留最优的性能表现,不需要修改row对象或者SelectionModel的原有逻辑。
实现步骤
- 新建纯管道
IsSelectedPipe
import { Pipe, PipeTransform } from '@angular/core'; import { SelectionModel } from '@angular/cdk/collections'; @Pipe({ name: 'isSelected', pure: true }) export class IsSelectedPipe implements PipeTransform { transform<T>(row: T, selection: SelectionModel<T>, _trigger: T[] = selection.selected): boolean { return selection.isSelected(row); } }
- 将管道注册到对应模块的
declarations数组中 - 替换模板中的绑定逻辑
<mat-checkbox [checked]="row | isSelected:selection:selection.selected" ...></mat-checkbox>
说明
- 额外传入
selection.selected作为触发参数,是因为CDK SelectionModel每次修改选中项时都会生成新的selected数组引用,会自动触发纯管道重新计算,不会出现状态不同步的问题 - 纯管道仅在输入参数引用变化时执行,不会在每次变更检测时重复计算,性能开销极低
方案2:行内禁用lint规则(折中方案)
如果你的表格数据量不大,selection.isSelected本身是O(1)复杂度的轻量操作,不会产生明显性能问题,可以直接针对该行代码禁用lint规则,不需要修改业务逻辑:
<!-- eslint-disable-next-line @angular-eslint/template/no-call-expression --> <mat-checkbox [checked]="selection.isSelected(row)" ...></mat-checkbox>
说明
- 该方案仅绕过lint检查,原有方法调用的执行逻辑不变,适合小范围、低数据量的场景使用
- 不建议在超大规模表格(千行以上)中使用该方案
内容的提问来源于stack exchange,提问作者Rune G
相关产品推荐
相关产品推荐

