Kendo Angular UI:保留stopPropagation时点击其他下拉关闭已展开项
解决方案
要实现点击任意动态生成的Kendo DropdownButton时关闭其他已展开的下拉面板,同时保留event.stopPropagation(),可以通过以下步骤实现:
1. 导入依赖并获取所有DropdownButton实例
在组件类中导入Angular的ViewChildren、QueryList以及Kendo的DropdownButtonComponent,通过@ViewChildren装饰器获取页面上所有DropdownButton的实例:
import { Component, ViewChildren, QueryList } from '@angular/core'; import { DropdownButtonComponent } from '@progress/kendo-angular-buttons'; @Component({ // 组件元数据(selector、template等) }) export class YourComponent { public toolbarData = [ { text: "Bold", iconClass: "fas fa-bold" }, { text: "Italic", iconClass: "fas fa-italic" }, { text: "Strike", iconClass: "fas fa-strikethrough" }, { text: "GIF", iconClass: "fas fa-image" } ]; // 存储所有DropdownButton实例(自动捕获动态生成的组件) @ViewChildren(DropdownButtonComponent) dropdownButtons!: QueryList<DropdownButtonComponent>; onDropdownButtonClick(event: Event, currentBtn: DropdownButtonComponent) { event.stopPropagation(); // 遍历所有下拉按钮,关闭非当前按钮的展开面板 this.dropdownButtons.forEach(btn => { if (btn !== currentBtn && btn.expanded) { btn.toggle(false); } }); } }
2. 修改模板绑定点击事件
无论是静态还是动态生成的DropdownButton,都需要添加模板引用变量(如#btn),并将点击事件绑定到组件的处理函数,同时传递当前按钮实例:
静态按钮示例:
<div> <kendo-dropdownbutton [data]="toolbarData" (click)="onDropdownButtonClick($event, btn)" #btn> User Settings<img src="../assets/images/arrow.svg" /> </kendo-dropdownbutton> <kendo-dropdownbutton [data]="toolbarData" (click)="onDropdownButtonClick($event, btn)" #btn> User Settings<img src="../assets/images/arrow.svg" /> </kendo-dropdownbutton> </div>
动态生成按钮示例(使用*ngFor):
<div> <kendo-dropdownbutton *ngFor="let btnItem of dynamicButtonList" [data]="toolbarData" (click)="onDropdownButtonClick($event, btn)" #btn> {{ btnItem.buttonText }}<img src="../assets/images/arrow.svg" /> </kendo-dropdownbutton> </div>
实现原理
@ViewChildren会自动捕获页面中所有DropdownButtonComponent实例,包括动态生成的组件,当组件列表变化时QueryList会自动更新。- 点击按钮时先执行
event.stopPropagation()保留原有逻辑,再遍历所有按钮实例:- 排除当前点击的按钮
- 对已展开(
btn.expanded为true)的按钮调用toggle(false)方法关闭下拉面板
内容的提问来源于stack exchange,提问作者Anjali Patel
相关产品推荐
相关产品推荐

