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

Angular中如何根据点击按钮动态设置ngb Accordion的activeIds

实现方案
  • 第一步:给模态框内的手风琴组件添加输入属性,用来接收外部传入的默认打开面板ID
    在acc-in-modal.component.ts中添加代码:
    import { Component, Input } from '@angular/core';
    // 原有导入逻辑保持不变
    @Component({
      // 原有组件配置保持不变
    })
    export class AccInModalComponent {
      // 新增输入属性,默认值设为Acc1,直接适配button1的默认打开需求
      @Input() defaultOpenPanel: string = 'Acc1';
      // 原有组件逻辑保持不变
    }
    
  • 第二步:修改手风琴模板,绑定activeId属性到新增的输入变量
    在acc-in-modal.component.html中修改手风琴相关代码:
    <!-- 绑定activeId到输入属性 -->
    <ngb-accordion [activeId]="defaultOpenPanel" #acc="ngbAccordion">
      <!-- 确认每个面板的id和传入的参数值对应,比如第一个面板id为Acc1,第二个为Acc2 -->
      <ngb-panel id="Acc1" title="面板1">
        <ng-template ngbPanelContent>
          面板1内容
        </ng-template>
      </ngb-panel>
      <ngb-panel id="Acc2" title="面板2">
        <ng-template ngbPanelContent>
          面板2内容
        </ng-template>
      </ngb-panel>
    </ngb-accordion>
    
  • 第三步:父组件触发模态框时,根据点击的按钮传入对应面板ID
    在父组件的按钮点击事件中,调用模态框打开方法后给组件实例传入对应值:
    // button1点击事件
    openModalForBtn1() {
      const modalRef = this.modalService.open(AccInModalComponent);
      // 不额外传值的话默认就是Acc1,也可以显式传入参数
      // modalRef.componentInstance.defaultOpenPanel = 'Acc1';
    }
    
    // button2点击事件
    openModalForBtn2() {
      const modalRef = this.modalService.open(AccInModalComponent);
      modalRef.componentInstance.defaultOpenPanel = 'Acc2';
    }
    

如果你遇到模态框渲染完成后activeId不生效的情况,可以在子组件的ngAfterViewInit生命周期钩子中手动调用手风琴的展开方法,代码如下:

import { AfterViewInit, ViewChild } from '@angular/core';
import { NgbAccordion } from '@ng-bootstrap/ng-bootstrap';

export class AccInModalComponent implements AfterViewInit {
  @Input() defaultOpenPanel: string = 'Acc1';
  @ViewChild('acc') accordion!: NgbAccordion;

  ngAfterViewInit(): void {
    this.accordion.expand(this.defaultOpenPanel);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:39:00