Search code examples
angulartextselectionexeccommand

select editable text on focus with execCommand


I've got a simple code that is suppose to select all contents of the element that was focused:

html:

  <div tabindex="-1" class="data" contenteditable="true"  (focusin)="focusin($event)" (focusout)="focusout($event)"  >Content</div>

.ts:

focusin(e) {
  console.log("focusin");
  document.execCommand("selectall");
}

The problem is that this code selects all text in the document, not just the one that was focused in. From what I see on the web, this is not how select all should work, if an element is focused:

How to select all text in contenteditable div?

Is there a fix for this?


Solution

  • Here is a solution that works for Chrome and most recent browsers versions :

    focusin(e) {
      var range = document.createRange();
      range.selectNodeContents(e.target);
      var sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(range);
    }