Angular中Ag-grid点击侧边栏外部区域时隐藏列侧边栏的实现问题
Angular + Ag-Grid 侧边栏点击外部自动隐藏实现方案
你可以通过全局点击事件监听 + DOM 区域判断 + Ag-Grid 官方API结合的方式实现,具体步骤如下:
- 第一步:在你的组件中获取Ag-Grid实例,同时给触发侧边栏显隐的按钮加模板引用,方便后续做区域排除
模板代码示例:<!-- 显隐侧边栏的按钮,加模板引用 --> <button #sidebarToggleBtn (click)="toggleSidebar()">切换侧边栏</button> <!-- Ag-Grid 表格,加模板引用获取实例 --> <ag-grid-angular #agGrid style="width: 100%; height: 500px;" class="ag-theme-alpine" [rowData]="rowData" [columnDefs]="columnDefs" [sideBar]="true" ></ag-grid-angular> - 第二步:在组件类中实现监听逻辑,用
@HostListener监听全局点击事件,判断点击区域是否在侧边栏/触发按钮之外,满足条件则隐藏侧边栏
组件类代码示例:import { Component, ViewChild, ElementRef, HostListener } from '@angular/core'; import { AgGridAngular } from 'ag-grid-angular'; @Component({ selector: 'app-my-grid', templateUrl: './my-grid.component.html', styleUrls: ['./my-grid.component.css'] }) export class MyGridComponent { @ViewChild('agGrid') agGrid!: AgGridAngular; // 获取触发按钮的DOM引用 @ViewChild('sidebarToggleBtn') sidebarToggleBtn!: ElementRef<HTMLElement>; // 原有按钮切换侧边栏的逻辑 toggleSidebar() { const currentVisible = this.agGrid.api.getSideBar().isVisible(); this.agGrid.api.getSideBar().setVisible(!currentVisible); } // 监听全局点击事件 @HostListener('document:click', ['$event']) handleClickOutside(event: MouseEvent) { // 先判断侧边栏当前是打开状态才做后续处理 if (!this.agGrid?.api?.getSideBar()?.isVisible()) return; // 获取侧边栏的DOM元素 const sidebarEl = document.querySelector('.ag-side-bar') as HTMLElement; // 点击的目标元素 const targetEl = event.target as HTMLElement; // 判断点击区域是否在侧边栏内部,或者是触发按钮本身 const isClickInsideSidebar = sidebarEl?.contains(targetEl); const isClickOnToggleBtn = this.sidebarToggleBtn.nativeElement.contains(targetEl); // 两者都不满足的话,隐藏侧边栏 if (!isClickInsideSidebar && !isClickOnToggleBtn) { this.agGrid.api.getSideBar().setVisible(false); } } } - 注意事项:
- 如果你的Ag-Grid配置了自定义侧边栏类名,需要把上面代码中查询侧边栏的选择器
.ag-side-bar替换成你自定义的类名 - 如果页面存在多个Ag-Grid实例,可以给当前表格加自定义类名限定查询范围,避免误操作其他表格的侧边栏
- 如果要兼容弹窗等特殊场景,可以自行扩展排除的DOM区域逻辑即可
- 如果你的Ag-Grid配置了自定义侧边栏类名,需要把上面代码中查询侧边栏的选择器
内容的提问来源于stack exchange,提问作者Prashant Karle
相关产品推荐
相关产品推荐

