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

Angular 4中实现双击ngb-accordion标题打开模态框的方法

实现双击ngb-accordion标题打开模态框

当然可以实现这个需求!默认的ngb-accordion面板标题是纯文本属性,没法直接绑定事件,所以我们需要自定义面板标题模板来添加双击事件,同时保留原有的单击展开/折叠功能。

具体实现步骤和代码示例:

首先,在你的组件模板中,把原来的title属性替换成<ng-template ngbPanelTitle>,在这个模板里编写标题内容并绑定双击事件;同时添加模态框的模板:

<ngb-accordion>
  <ngb-panel id="toggle-2">
    <!-- 自定义面板标题模板 -->
    <ng-template ngbPanelTitle>
      <span (dblclick)="openModal(modalContent)">Second</span>
    </ng-template>
    <ng-template ngbPanelContent>
      Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
    </ng-template>
  </ngb-panel>
</ngb-accordion>

<!-- 模态框模板 -->
<ng-template #modalContent let-modal>
  <div class="modal-header">
    <h4 class="modal-title">面板标题双击触发的模态框</h4>
    <button type="button" class="btn-close" aria-label="Close" (click)="modal.dismiss('Cross click')"></button>
  </div>
  <div class="modal-body">
    这里是模态框的内容,可以根据你的需求自定义!
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-outline-dark" (click)="modal.close('Save click')">关闭</button>
  </div>
</ng-template>

然后在你的组件类中,注入NgbModal服务,并实现打开模态框的方法:

import { Component } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponentComponent {
  constructor(private modalService: NgbModal) {}

  openModal(content: any) {
    this.modalService.open(content);
  }
}

说明:

  • 我们通过<ng-template ngbPanelTitle>自定义了标题区域,在标题文本的<span>上绑定了dblclick事件,触发组件的openModal方法打开模态框。
  • 原有的单击展开/折叠功能完全保留,因为双击事件不会阻止单击的默认行为(ng-bootstrap的accordion标题区域默认的单击事件依然生效)。
  • 模态框的内容可以根据你的需求完全自定义,包括样式、结构和交互逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:22:43