Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

string - Angular get clicked word in a text

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!

question from:https://stackoverflow.com/questions/65894138/angular-get-clicked-word-in-a-text

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...