You need to enable JavaScript to run this app. Angular自定义手风琴无法实现单次仅展开一个面板问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Angular自定义手风琴无法实现单次仅展开一个面板问题求助

问题修复方案

原代码问题说明

  • 每次触发点击事件时都会循环给手风琴元素重复绑定click回调,逻辑完全错误,无法正常执行
  • 没有存储当前激活面板的索引,无法定位到之前打开的面板做状态清除
  • 手动操作DOM不符合Angular开发规范,维护成本高

最小改动修复方案

你可以直接替换原有逻辑实现单次仅展开一个面板的效果:

  1. 组件类先新增变量存储当前激活的面板索引
activeIndex: number | null = null;
  1. 替换toggleAccordian方法的全部逻辑:
toggleAccordian(event: MouseEvent, index: number) {
  const clickedElement = event.target as HTMLElement;
  const clickedPanel = clickedElement.nextElementSibling as HTMLElement;

  // 点击已激活的面板则直接收起
  if (this.activeIndex === index) {
    clickedElement.classList.remove('active');
    clickedPanel.style.maxHeight = null;
    this.activeIndex = null;
    return;
  }

  // 清空所有已激活的面板状态
  const allAccordions = document.querySelectorAll('.accordion') as NodeListOf<HTMLElement>;
  const allPanels = document.querySelectorAll('.panel') as NodeListOf<HTMLElement>;
  allAccordions.forEach(el => el.classList.remove('active'));
  allPanels.forEach(panel => panel.style.maxHeight = null);

  // 激活当前点击的面板
  clickedElement.classList.add('active');
  clickedPanel.style.maxHeight = `${clickedPanel.scrollHeight}px`;
  this.activeIndex = index;

  // 保留原有业务逻辑
  this.displayBreadCrumbText = null;
  this.moduleNameStr = null;
  this.moduleGroupText = clickedElement.innerText;
}

更推荐的Angular响应式实现

无需手动操作DOM,通过Angular的绑定能力自动同步状态与DOM,更易维护:

  1. 修改模板代码:
<div *ngFor="let items of moduleGroup; let i = index">
  <button 
    class="accordion" 
    [class.active]="activeIndex === i"
    (click)="toggleAccordian(i, items.moduleGroupName)"
  >
    {{items.moduleGroupName}}
  </button>
  <div 
    class="panel" 
    [style.maxHeight]="activeIndex === i ? panel.scrollHeight + 'px' : null"
    #panel
  >
      <p *ngFor="let modules of items.moduleList"> 
        <a href="javascript:void(0)" (click)="getRoleModulePermissionById($event,modules.id)">{{modules.moduleName}}</a> 
      </p>
  </div>
</div>
  1. 组件逻辑简化为:
activeIndex: number | null = null;

toggleAccordian(index: number, groupName: string) {
  // 点击已激活面板则收起,否则激活当前面板
  this.activeIndex = this.activeIndex === index ? null : index;
  // 原有业务逻辑
  this.displayBreadCrumbText = null;
  this.moduleNameStr = null;
  this.moduleGroupText = groupName;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 17:27:03