I’m trying to build a basic Rich Text Editor with Ionic, and to do so, I need a way to get the current position of the user’s cursor in the text box. This is for the purpose of bolding text inline. However, I cannot find any property that would let me do this. Does anyone have an idea as to how to do this? Maybe I need to use something other than ion-textarea.
HII I have done this in my project
one .html site you have to use Reference Variables (#input)
here is html code
<ion-textarea rows="2" #input>
</ion-textarea>
on ts side inport viewchild its used to bind element attribute
import {ViewChild} from '@angular/core';
export class Page {
@ViewChild('input') myInput ;
}
````this.myInput.setFocus();
`
Thanks for your reply! I’m still confused, however on how I can get the node’s selection. So, in pure JS, I could use the textarea object’s selectionStart function, and this would return the cursor position in the text field. Is there a way to expand on what you have to do this?
send me your .html and .ts file
I am having the same issue, please post the solution to this. I want to get the selectionStart from an ion-textarea when a button is clicked.
Thanks
Joel Stevick
Try the code below
for Ionic React
// checked with ionInput. IonTextArea could have similar logic
...
const handle_onKeyUp = (event: React.KeyboardEvent<HTMLIonInputElement>) => {
console.log('selectionStart')
event.currentTarget.getInputElement().then(el => console.log(el.selectionStart))
console.log('selectionEnd')
event.currentTarget.getInputElement().then(el => console.log(el.selectionEnd)
}
...
// in the location where ionInput is used
<IonInput onKeyUp={e => handle_onKeyUp(e)} ></IonInput>
...
This works in Ionic 8, Vue 3.5 The problem seems to be that with an ion-text-area element, unlike a regular text-area element, it doesn’t have the .selectStart and .selectEnd attritubes, but you can dig inside of the ion-text-area element to find the text-area element via it’s “native-textarea” className. The following example is for insert text at the cursor position broken down from something else I used it for.
html
<ion-textarea
v-model=“text”
ref=“textAreaRef”>
</ion-textarea>
<ion-button @click=“insertText(“Test”)”>
</ion-button>
type script
import { ref } from ‘vue’;
var text = ref(“”);
var textAreaRef= ref();
function insertText(textToInsert: string)
{
const textAreaElement = textAreaRef.value?.$el.querySelector(“.native-textarea”);
if (textAreaElement)
{
//You might not need this
textAreaElement.focus();
const start = textAreaElement.selectionStart;
const end = textAreaElement.selectionEnd;
const newValue =
text .value.substring(0, start) +
textToInsert +
text .value.substring(end);
text .value = newValue;
//You might not need this
textAreaElement.focus();
}
}
You could also get the ion-text-area by id instead and do something like this to get the text-area within
const textAreaElement = document.getElementById(“<ion-text-area-id>”)?.$el.querySelector(“.native-textarea”);