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

Angular嵌套Mat Select添加过滤及展开交互问题求助

解决Angular Material嵌套下拉菜单的两个问题

我来帮你搞定这两个嵌套下拉菜单的问题,咱们一步步来:

1. 修复自动提示并自动展开匹配的父级视图

问题核心是要让搜索关键词既能匹配父级名称,也能匹配子级名称,并且自动展开那些包含匹配项的父级面板。

首先,你需要在组件里维护两个状态:

  • 过滤后的父级选项列表
  • 一个对象来跟踪哪些父级处于展开状态

组件代码修改:

// 定义过滤后的选项和展开状态对象
filteredOptions: any[];
expandedParentIds: { [key: string]: boolean } = {};

// 过滤逻辑函数
filterOptions(event: Event) {
  const searchTerm = (event.target as HTMLInputElement).value.trim().toLowerCase();
  
  // 如果搜索词为空,恢复全部选项并收起所有面板
  if (!searchTerm) {
    this.filteredOptions = [...this.options];
    this.expandedParentIds = {};
    return;
  }

  // 过滤父级:匹配父级名称 或 子级名称包含搜索词
  this.filteredOptions = this.options.filter(parent => {
    const matchesParent = parent.name.toLowerCase().includes(searchTerm);
    const matchesChild = parent.children.some(child => child.name.toLowerCase().includes(searchTerm));
    const isMatch = matchesParent || matchesChild;

    // 自动展开匹配的父级,不匹配的则收起
    this.expandedParentIds[parent.id] = isMatch;
    return isMatch;
  });
}

模板代码修改:

把展开状态绑定到expandedParentIds[parent.id],同时确保自动提示的数据源是过滤后的列表:

<mat-form-field>
  <input type="text" matInput [formControl]="myControl" [matAutocomplete]="auto" (input)="filterOptions($event)">
  <mat-autocomplete #auto="matAutocomplete">
    <mat-accordion>
      <mat-expansion-panel 
        *ngFor="let parent of filteredOptions" 
        [expanded]="expandedParentIds[parent.id]"
      >
        <mat-expansion-panel-header>
          <mat-panel-title>{{ parent.name }}</mat-panel-title>
        </mat-expansion-panel-header>
        <mat-option *ngFor="let child of parent.children" [value]="child">
          {{ child.name }}
        </mat-option>
      </mat-expansion-panel>
    </mat-accordion>
  </mat-autocomplete>
</mat-form-field>

这样一来,不管你输入父级还是子级的名称,对应的父级都会被过滤出来并自动展开,方便选择子项。

2. 展开新父级时自动收起其他父级

这个需求可以通过监听mat-expansion-panel的opened事件来实现,当某个父级面板展开时,把其他所有父级的展开状态设为false即可。

组件添加方法:

onPanelOpened(parentId: string) {
  // 遍历所有已记录的父级ID,将它们的展开状态设为false
  Object.keys(this.expandedParentIds).forEach(id => {
    this.expandedParentIds[id] = false;
  });
  // 把当前展开的父级设为true
  this.expandedParentIds[parentId] = true;
}

模板绑定事件:

给mat-expansion-panel添加opened事件绑定:

<mat-expansion-panel 
  *ngFor="let parent of filteredOptions" 
  [expanded]="expandedParentIds[parent.id]"
  (opened)="onPanelOpened(parent.id)"
>

现在,当你展开第二个父级面板时,第一个会自动收起,保证同一时间只有一个父级处于展开状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 17:22:44