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

如何在Angular TS文件中编写通用工具函数合并两个移除项函数

合并Angular中重复的移除项函数

步骤1:编写通用移除函数

替换TS文件中两个重复的移除函数,改成一个通用函数,通过属性名指定要操作的数组:

removeItem(propName: 'selectedSrcLocFlexItems' | 'selectedWrkLocFlexItems', item: any): void {
  // 过滤目标项并重新赋值,触发Angular变更检测更新UI
  this[propName] = this[propName].filter(t => t !== item);
}

这里用联合类型限定propName的可选值,避免传入错误属性名,保证类型安全。

步骤2:更新模板中的点击事件

修改HTML文件里的按钮点击事件,调用通用的removeItem函数,传入对应属性名和当前项:

<ng-container *ngIf="selectedSrcLocFlexItems.length">
  <div *ngFor="let item of selectedSrcLocFlexItems;"
       class="dropdown-tags mt-2 p-1 px-2 d-inline-flex align-items-center justify-content-between">
    {{item}}
    <button class="smart-icon-close smart-btn btn" 
            (click)="removeItem('selectedSrcLocFlexItems', item)"
            aria-label="close button" type="button"></button>
  </div>
</ng-container>
<ng-container *ngIf="selectedwrkLocFlexItems.length">
  <div *ngFor="let item of selectedwrkLocFlexItems;"
       class="dropdown-tags mt-2 p-1 px-2 d-inline-flex align-items-center justify-content-between">
    {{item}}
    <button class="smart-icon-close smart-btn btn" 
            (click)="removeItem('selectedWrkLocFlexItems', item)"
            aria-label="close button" type="button"></button>
  </div>
</ng-container>

原理说明

  • 通用函数通过属性名动态访问组件数组,消除重复逻辑
  • filter返回新数组并重新赋值,会触发Angular变更检测,确保UI实时同步选中项的变化

内容的提问来源于stack exchange,提问作者Ram

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 12:20:22