You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Angular模板绑定调用isSelected触发no-call-expression lint错误

@angular-eslint/template/no-call-expression 规则禁止在模板绑定中直接调用方法,核心是为了避免变更检测频繁触发方法执行导致性能损耗,针对你的场景有两种可行方案:


方案1:使用纯管道(推荐)

该方案完全符合lint规则,同时保留最优的性能表现,不需要修改row对象或者SelectionModel的原有逻辑。

实现步骤

  1. 新建纯管道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);
  }
}
  1. 将管道注册到对应模块的declarations数组中
  2. 替换模板中的绑定逻辑
<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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 10:54:04