3

I'm trying to create a custom simple text editor so I can color certain pieces of text as the user types. So for some pieces I may want to make green, others blue. To do this I need to bind my content to the innerHTML property of the div which is working fine to initially display my content. (I can see my html rendering in the div).

<div class="textarea-editor" contenteditable="true" [innerHTML]="getBuiltRules" (input)="onRuleEditorFullKeyUp($event.target.innerHTML)"></div>

Then in the input event, I'm grabbing the current innerHTML and want to search and surround certain strings with <span class='color-green'></span> so this text would show green, then I want to have the changes rendered back to the div.

onRuleEditorFullKeyUp(value: string) { // search and surround some text with html tags then set a variable this.setBuiltRules = value; }

The issue i'm having is once I set setBuiltRules = value, it seems to re-bind the innerHTML and the carat position goes to the very beginning. So if i'm typing something, it goes to the beginning after each character.

Is there a better way to do this so I don't lose my cursor position?

Note: setBuiltRules and getBuiltRules reference a service property.

Michael
  • 37
  • 5
  • I answered such a question regarding input elements, but I guess you can apply it to your problem https://stackoverflow.com/questions/43492421/angular-2-cursor-jump-at-the-end-of-textbox-when-changing-data/43492808#43492808 – n00dl3 Jul 23 '18 at 12:41

0 Answers0