如何为AG-Grid自定义上下文菜单项添加带独立点击事件的图标
AG-Grid 上下文菜单拆分点击事件实现
要实现点击菜单项文本调用alertOne()、点击图标调用alertTwo()的效果,核心是利用AG-Grid自定义菜单项的template属性,自定义菜单项的HTML结构,为文本和图标分别绑定独立的点击事件。
完整代码实现
getContextMenuItems(params: GetContextMenuItemsParams): (string | MenuItemDef)[] { // 保留组件实例引用,避免箭头函数this指向问题 const self = this; const result: (string | MenuItemDef)[] = [ { template: ` <div style="display: flex; justify-content: space-between; align-items: center; padding: 6px 12px; cursor: default;"> <span onclick="(() => { self.alertOne('${params.value}') })()" style="cursor: pointer;">Alert</span> <span onclick="(() => { self.alertTwo('${params.value}') })()" style="cursor: pointer;">(:D)</span> </div> ` } ]; return result; } alertOne(value: string) { window.alert('Alerting about ' + value); } alertTwo(value: string) { window.alert('Icon clicked: ' + value); }
关键说明
- 使用
template替代默认的name属性,自定义菜单项的HTML布局,通过flex实现文本左对齐、图标右对齐的效果。 - 为文本和图标分别添加
onclick事件,通过保留的组件实例self调用对应的方法,并传递行数据的值params.value。 - 为可点击元素添加
cursor: pointer样式,提升用户交互体验。
内容的提问来源于stack exchange,提问作者Oam Psy
相关产品推荐
相关产品推荐

