0

The user can type a text in a div that has the attribute contenteditable="true" and they can also select a text. I now would like to output the selected text.

This is what I have tried:

<div (select)="getSelectedText()" contenteditable="true" #editor id="editor"></div>
getSelectedText(): void {
  console.log(window.getSelection());
}

This is not working, probably because (select) is not available for div. This is what the documentation of it says:

Element: select event

The select event fires when some text has been selected.

...

The event is not available for all elements in all languages. For example, in HTML, select events can be dispatched only on form <input type="text"> and <textarea> elements.

Is there an alternative to this in Angular?

Vega
  • 27,856
  • 27
  • 95
  • 103
xRay
  • 543
  • 1
  • 5
  • 29
  • 1
    Does this answer your question? [HTML Content Editable div: select text event](https://stackoverflow.com/questions/13285877/html-content-editable-div-select-text-event) – CBroe Jun 24 '22 at 13:48
  • @CBroe no. My question is related to Angular only. Not jQuery or JavaScript. – xRay Jun 24 '22 at 13:55
  • So what, that doesn't change the fact that you need to use a different event to begin with. – CBroe Jun 24 '22 at 14:10

2 Answers2

1

There is not much you can do but to listen either mouse, either to keyup event:

HTML

<div (keyup)="getSelectedText()" (mouseup)="getSelectedText()" contenteditable="true" #editor id="editor"></div>

TS

  getSelectedText(){
    console.log(document.getSelection()?.toString())
  }

Demo

Vega
  • 27,856
  • 27
  • 95
  • 103
  • 1
    Just what I wanted, thank you! However, `document.getSelection().toString()` gave me the error *TS2531: Object is possibly 'null'.*. I have now changed it to `document.getSelection()?.toString()` and it works fine. – xRay Jun 24 '22 at 14:47
  • I edited the post to take in account the correction – Vega Jun 24 '22 at 15:12
0

You should use a mouseup and mouseout event in your div and then call window.getSelection().toString() to get the selected text.

<div (mouseup)="getSelectedText()" (mouseout)="getSelectedText()"contenteditable="true" #editor id="editor"></div>

getSelectedText(): void {
   if (window.getSelection) {
        window.getSelection().toString();
    }
}

Ref : Get the Highlighted/Selected text

Maff_31
  • 1
  • 1