Angular get clicked word in a text

Viewed 898

In Angular, how can I get the word that has just been clicked or double clicked by the user ?

What I want to do is this : the user double click a word in a text then the text is highlighted.

Text: "This is just some text"

the user clicks on the word "just" > I get it in the TS.

I have googled it but the only info I found are 10 years old threads in Angular JS.

Thanks in advance!

2 Answers

You can achieve it by getting the selected word from text and replacing it with HTML tag to highlight it.

Here is the working example -

export class AppComponent {
  text = "Start editing to see some magic happen";
  selectedWord: string;

  highlight(event) {
    this.selectedWord = window.getSelection().toString();
    this.text = this.text.replace(
      this.selectedWord,
      "<mark>" + this.selectedWord + "</mark>"
    );
  }
}

In the html file, you need to use innerHTML for text and call highlight() method on doubleclick event like this -

<p [innerHTML]="text" (dblclick)="highlight($event)"></p>

Here is also a stackbiltz working example.

For this you need to use hostListner to monitor dblclick. please check the following

@HostListener('document:dblclick', ['$event'])
  onMouseDown(event) {
      let selectedText:any = ''; 

      if (window.getSelection) { 
          selectedText = window.getSelection().toString(); 
      } else if (document.getSelection) { 
          selectedText = document.getSelection().toString(); 
      } 
      console.log(selectedText);
      return; 
  }

i think this will help for you

Related