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

Angular13+TypeScript:用Mat组件实现可搜索多选复选框输入框

实现Angular Material 13集成搜索的多选复选框组件

Angular Material 13确实没有原生提供这种集成搜索框的多选复选组件,不过可以通过组合现有Mat组件实现类似需求,以下是具体实现方案:

核心实现思路

通过开启多选模式的MatSelect嵌套MatInput作为搜索框,结合过滤逻辑动态渲染可选项,同时保留多选复选框的交互逻辑。

1. 组件模板实现

<mat-form-field appearance="fill">
  <mat-label>选择选项</mat-label>
  <mat-select [formControl]="selectedOptions" multiple panelClass="select-panel">
    <!-- 搜索输入框 -->
    <div class="search-container">
      <input matInput placeholder="搜索选项" [(ngModel)]="searchKeyword" (input)="filterOptions()">
    </div>
    <!-- 过滤后的选项列表 -->
    <mat-option *ngFor="let option of filteredOptions" [value]="option.value">
      {{option.label}}
    </mat-option>
  </mat-select>
</mat-form-field>

2. TypeScript逻辑实现

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';

interface SelectOption {
  label: string;
  value: string;
}

@Component({
  selector: 'app-search-multi-select',
  templateUrl: './search-multi-select.component.html',
  styleUrls: ['./search-multi-select.component.scss']
})
export class SearchMultiSelectComponent implements OnInit {
  selectedOptions = new FormControl<string[]>([]);
  searchKeyword = '';
  // 原始选项列表,可替换为业务数据
  allOptions: SelectOption[] = [
    { label: '中国', value: 'CN' },
    { label: '美国', value: 'US' },
    { label: '日本', value: 'JP' },
    { label: '德国', value: 'DE' }
  ];
  filteredOptions: SelectOption[] = [];

  ngOnInit(): void {
    this.filteredOptions = [...this.allOptions];
  }

  filterOptions(): void {
    if (!this.searchKeyword.trim()) {
      this.filteredOptions = [...this.allOptions];
      return;
    }
    const keyword = this.searchKeyword.toLowerCase();
    this.filteredOptions = this.allOptions.filter(option => 
      option.label.toLowerCase().includes(keyword)
    );
  }
}

3. 样式调整(SCSS)

默认MatSelect的下拉面板样式需要调整,让搜索框更贴合整体交互:

.select-panel {
  .search-container {
    padding: 8px 16px;
    border-bottom: 1px solid rgba(0,0,0,0.12);
    input {
      width: 100%;
    }
  }
}

::ng-deep .mat-select-panel-wrap {
  max-height: 300px;
}

可选优化

  • 将过滤逻辑封装为Angular Pipe,提升复用性:

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({ name: 'optionFilter' })
    export class OptionFilterPipe implements PipeTransform {
      transform(options: SelectOption[], keyword: string): SelectOption[] {
        if (!keyword.trim()) return options;
        const lowerKeyword = keyword.toLowerCase();
        return options.filter(opt => opt.label.toLowerCase().includes(lowerKeyword));
      }
    }
    

    模板中直接使用:*ngFor="let option of allOptions | optionFilter: searchKeyword"

  • 添加已选标签展示:在MatSelect上方添加标签组,直观显示已选中的选项,优化用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 14:18:31