如何在Angular Kendo上下文菜单中实现点击菜单项插入对应文本的功能
实现步骤
1. 调整组件模板(component.html)
给Kendo上下文菜单绑定select事件(处理菜单项点击逻辑)和popupOpen事件(记录触发菜单时的目标元素与光标位置),参考代码如下:
<!-- 示例为文本域触发,可根据你的业务替换为对应触发区域 --> <textarea #editArea></textarea> <kendo-contextmenu [items]="items" [target]="editArea" (select)="onMenuItemSelect($event)" (popupOpen)="onPopupOpen($event)" > </kendo-contextmenu>
2. 完善组件逻辑(component.ts)
新增临时变量存储触发菜单时的元素和光标位置,实现对应事件方法:
import { Component } from '@angular/core'; import { ContextMenuSelectEvent, ContextMenuPopupOpenEvent } from '@progress/kendo-angular-menu'; @Component({ // 你的原有组件配置 }) export class YourComponent { // 你原有菜单项配置 public items: any[] = [ { text: "hello", items: [{ text: "Item1.1" }, { text: "Item1.2" }], }, { text: "Item2", }, { text: "hello2", } ]; // 临时存储触发菜单的元素和光标位置 private lastActiveElement: HTMLInputElement | HTMLTextAreaElement | null = null; private cursorPosition: number = 0; // 菜单打开时记录触发元素与光标位置 public onPopupOpen(event: ContextMenuPopupOpenEvent): void { const target = event.originalEvent.target as HTMLElement; // 适配输入框/文本域场景,可根据业务调整判断条件 if (['INPUT', 'TEXTAREA'].includes(target.tagName)) { this.lastActiveElement = target as HTMLInputElement | HTMLTextAreaElement; this.cursorPosition = this.lastActiveElement.selectionStart || 0; } } // 菜单项点击时插入文本到对应位置 public onMenuItemSelect(event: ContextMenuSelectEvent): void { if (!this.lastActiveElement) return; const insertText = event.item.text; const inputDom = this.lastActiveElement; const originValue = inputDom.value; // 拼接文本并替换输入框值 inputDom.value = originValue.slice(0, this.cursorPosition) + insertText + originValue.slice(this.cursorPosition); // 光标移动到插入文本的末尾 const newCursorPos = this.cursorPosition + insertText.length; inputDom.selectionStart = inputDom.selectionEnd = newCursorPos; // 触发input事件同步Angular双向绑定的值 inputDom.dispatchEvent(new Event('input')); // 清空临时存储 this.lastActiveElement = null; } }
适配说明
- 如果触发区域是
contenteditable属性的富文本容器,可直接替换插入逻辑为document.execCommand('insertText', false, insertText),无需手动计算光标位置。 - 上述逻辑天然支持多级子菜单的文本插入,点击任意层级的子菜单都会自动取对应菜单项的文本值插入。
内容的提问来源于stack exchange,提问作者Claudio Guedes
相关产品推荐
相关产品推荐

