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

如何在Mat-select-autocomplete组件中展示“未找到匹配结果”提示?

mat-select-autocomplete多选下拉添加「未找到结果」提示实现方案
  • 核心逻辑:监听搜索关键词变化后的过滤选项数组长度,当输入了搜索内容且过滤后数组为空时,展示禁用态的提示选项。

1. 组件逻辑调整

先在组件类中维护过滤后的选项列表、搜索控制器两个变量,每次搜索触发时更新过滤数组:

// 全量选项
allOptions = [
  {label: '选项1', value: 1},
  {label: '选项2', value: 2},
  // 其余选项
];
// 过滤后展示的选项
filteredOptions = [...this.allOptions];
// 搜索框控制器
searchCtrl = new FormControl('');
// 多选下拉控制器
selectControl = new FormControl([]);

ngOnInit() {
  // 监听搜索输入,实时过滤选项
  this.searchCtrl.valueChanges.subscribe(key => {
    const searchKey = (key || '').toLowerCase().trim();
    this.filteredOptions = this.allOptions.filter(opt => 
      opt.label.toLowerCase().includes(searchKey)
    );
  });
}

2. 模板逻辑调整

在下拉面板的选项循环后添加未找到结果的提示项,仅当输入了搜索内容且无匹配选项时展示:

<mat-select [formControl]="selectControl" multiple>
  <!-- 搜索框 -->
  <mat-select-search [formControl]="searchCtrl" placeholder="搜索选项"></mat-select-search>
  
  <!-- 正常选项循环 -->
  <mat-option *ngFor="let opt of filteredOptions" [value]="opt.value">
    {{opt.label}}
  </mat-option>
  
  <!-- 未找到结果提示 -->
  <mat-option 
    *ngIf="filteredOptions.length === 0 && searchCtrl.value" 
    disabled
    class="no-result-tip"
  >
    未找到结果
  </mat-option>
</mat-select>

3. 样式优化(可选)

给提示项添加样式,弱化显示同时避免用户误操作:

.no-result-tip {
  color: rgba(0,0,0,0.54);
  pointer-events: none;
  cursor: default;
}

注意事项

如果你的选项是异步请求获取的,需要额外添加加载状态判断,避免请求还未返回时提前显示「未找到结果」:

<mat-option 
  *ngIf="filteredOptions.length === 0 && searchCtrl.value && !isLoading" 
  disabled
  class="no-result-tip"
>
  未找到结果
</mat-option>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 22:45:02