Home > database >  (select) event doesn't work for div elements
(select) event doesn't work for div elements

Time:06-25

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?

CodePudding user response:

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

CodePudding user response:

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

  • Related