0

I have a div element with contenteditable attribute set to true.
the div has a 2 way binding to an angular class property.

the problem is when the text is changing via (input) event the cursor looses focus and the user have a bad UX while trying to edit the text inside the div.

basically i am trying to achive something like that (js):

divlft.focus();
divlft.selectionEnd = end; 

but if i try to cast the div to HTMLInputElement i get undefined value:

let txtlft = document.getElementById("divlft") as HTMLInputElement;
console.log(txtlft.selectionEnd); // delete

and if i try to cast the element to HTMLElement, clearly i can not access selectionEnd property

Html:

   <div class="txtAr txtleft" id="divlft"  contenteditable="true" [innerHTML]="LeftText | sanitizeHtml" (input)="textChanged($event.target.innerHTML)">


    </div>

type script textChange method:

public textChanged(value: string): void {
    let txtlft = document.getElementById("divlft") as HTMLInputElement;
    console.log(txtlft.selectionEnd); // delete
    this.LeftText = value;
    this.LeftText = "<span style='color: white;'>" + this.LeftText + "</span>";
    txtlft.focus();
    console.log(txtlft.selectionEnd)
}

I am very new to front end web development, so maybe i am missing something
basic but i did not succeed to search a solution for that.

How can i approach this problem?

Jonathan Applebaum
  • 5,738
  • 4
  • 33
  • 52
  • I don't know why casting fails, never used that though. But you may check the "placeCaretAtEnd" method in this answer; https://stackoverflow.com/a/4238971/3928819 It uses the range & selection APIs. – cdagli Aug 08 '17 at 08:19
  • @cdagli, thank you for the link, that is exactly what i am trying to do now. – Jonathan Applebaum Aug 08 '17 at 19:21

0 Answers0