问题
I am trying to create a custom textarea editor by adding contenteditable as attribute on a div element that the text will be as text element and hashtag will be as span element, but the problem is when i want to add a hashtag between text and hashtag, to do that must to find the current index of child element that the cursor is writing, and then i can use inderBefore method to add this element after this index thanks
my html code:
<div class="text">
<div #textarea class="textarea" contenteditable="true"
(input)="onchangeText($event)" (focusin)="toggleFocus()" (focusout)="toggleFocus()" >
that is a post <span class="hashtag">#hashtag</span> try to add hashtag at the
<span class="hashtag">#beginig</span> will be add as last child to the and
</div>
<div class="placeholder" *ngIf="checkPlaceHolder()" (click)="onclickPlaceHolder($event)"
[ngStyle]="{opacity:focus? 0.5 : 1}">
What do you want to share?
</div>
</div>
here is my input event handler:
onchangeText(event) {
// on input event handler
if (this.isAfterHashtag()) {
this.onAddElement(event.data, "text"); //add new element
}
if (this.isHashtag(event.data)) {
// if character is # hashtag
this.onAddElement(event.data, "hash");
}
this.setText();
if (this.checkPlaceHolder()) {// if the length of textare is 0
this.textarea.nativeElement.innerHTML = "";
}
}
here is my addElementMethod:
onAddElement(text, type) {
this.removeLastCharacter();
if (type === "hash") {
// add element for hash tag
const span: HTMLParagraphElement = this.renderer.createElement("span");
span.innerHTML = text;
this.renderer.addClass(span, "hashtag");
this.renderer.appendChild(this.textarea.nativeElement, span);
//must use insertBefore method, but before it must find index of child elemenet where to add it
// this.renderer.insertBefore( this.textarea.nativeElement , p , this.textarea.nativeElement.children[1] );
} else if (type === "text") {
// add element for text
const textNode = this.renderer.createText("");
textNode.textContent = text;
this.renderer.appendChild(this.textarea.nativeElement, textNode);
}
this.setText();
this.setCursorToEnd();
}
here is an example:
custom textarea editor
来源:https://stackoverflow.com/questions/59325570/how-to-find-the-child-node-element-of-a-div-contenteditable-where-the-cursor-i