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

Angular Material带筛选选择列表实现问题求助

问题:Angular Material筛选选择列表的选中状态跟踪与性能优化

我尝试使用Angular Material List Module创建带筛选功能的选择列表,目前功能已实现,但存在两个核心问题:

  • 筛选或取消筛选时,被筛选掉的选中项会被移除,导致选中状态的跟踪丢失;
  • 改用@for循环渲染mat-checkbox的方案中,需要调用isSelected函数判断每个列表项的选中状态,该函数会在任何变更时为所有列表项执行,性能开销极大。

现有代码如下:

HTML代码

<mat-form-field class="w-full">
   <mat-label>Filter</mat-label>
   <input matInput formControlName="itemFilter" (ngModelChange)="filterItem($event)" />
</mat-form-field>

<div class="w-full flex-column my-list d-flex align-items-center justify-content-start">
@for(s of filteredOptions; track s){
    <mat-checkbox class="w-full" [checked]="isSelected(s)" (click)="toggleSelected(s)">{{s.name}} ({{s.code}})</mat-checkbox>
}
</div>

Component代码

filterItem($event: any): void {
    if (!$event) {
      this.filteredOptions = this.origList;
    }
    if (typeof $event === 'string') {
      this.filteredOptions = this.origList.filter((a) =>
        a.name.toLowerCase().startsWith($event.toLowerCase())
      );
    }
  }


isSelected(item: MyItem): boolean {
    return (this.searchForm.get('selectedItems')?.value as MyItem[]).indexOf(item) > -1;
  }

toggleSelectedShed(item: MyItem) {
    const current = this.searchForm.get('selectedItems')
      ?.value as MyItem[];
    if (current.indexOf(item) > -1) {
      // Remove it
      current.splice(current.indexOf(item), 1);
    } else {
      // Add it
      current.push(item);
    }

    this.searchForm.get('selectedItems')?.patchValue(current);
  }

请问是否有其他方案可实现筛选功能,同时避免上述弊端?

我曾放弃筛选需求转而使用简单复选框数组,但该方案仍存在问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 12:50:20