Inserting Text at Cursor Position in the TextArea
Environment
| Product | Progress® Kendo UI® TextArea for Angular |
Description
I have a Kendo UI for Angular TextArea in my project and a context menu attached to the TextArea. When the user selects an entry from the context menu, I want to insert the selected value at the current cursor position in the TextArea.
This Knowledge Base article also answers the following questions:
- How can I insert text at the current cursor position in the TextArea?
- What is the method to detect the cursor position within the TextArea?
- How do I use a context menu to insert text at a specific position in the TextArea?
Solution
To insert text at the cursor position inside the Kendo UI for Angular TextArea:
-
Declare the TextArea and a Kendo UI for Angular ContextMenu in the template of your component:
html<kendo-textarea ...></kendo-textarea> <kendo-contextmenu #cmenu ...></kendo-contextmenu> -
Handle the generic
contextmenuevent of the TextArea component and prevent its default behavior.html<kendo-textarea #textarea ... (contextmenu)="openContextMenu($event)" ></kendo-textarea>tspublic openContextMenu(e) { e.preventDefault(); ... } -
Use the
contextmenuevent handler to obtain and store the current cursor position and programmatically display the ContextMenu.tspublic openContextMenu(e) { ... const textareaElement: HTMLTextAreaElement = document.querySelector('.k-input-inner'); const startPos = textareaElement.selectionStart; const endPos = textareaElement.selectionEnd; if (startPos === endPos) { this.cursorPosition = startPos; } this.contextMenu.show({ left: e.pageX, top: e.pageY, }); } -
Handle the
selectevent of the ContextMenu and insert the desired text at the cursor position by updating the value bound to the TextArea:tspublic onSelect(ev) { const item = ev.item.text; this.value = this.value.substring(0, this.cursorPosition) + item + this.value.substring(this.cursorPosition); }
The following example demonstrates the suggested approach in action.