0

I have a string and when i click on any word in a string then it should give another string from that clicked word onward back to the start of the string i.e.

str = 'this is a test string.' After click on "test" word, the new string should be like that 'this is a test' etc.

Currently, When I select the whole word then it gives the expected result but not on 'click'.

Also, in the following link they give the solution but it is in jquery and I want to implent in Anguar 10

Get a word by single click

app.component.html

<textarea class="form-control  rows=10 cols=50 cstm-textarea" (click)="TargetPrefix($event)">
    This is a test string
</textarea>

app.component.ts

TargetPrefix(event) {

    const start = event.target.selectionStart;
    const end = event.target.selectionEnd;
    const result = event.target.value.substr(end - start, start);

    console.log("the clicked word in the string", result);

}

[enter image description here][1] [enter image description here][2]

Thank you

onClick [1]: https://i.stack.imgur.com/qjwKO.jpg

Select [2]: https://i.stack.imgur.com/SG6zT.jpg

Atika.Akmal
  • 11
  • 1
  • 3

2 Answers2

1

Here you have an example of how to implement it in angular

https://stackblitz.com/edit/angular-ivy-prcewk?file=src%2Fapp%2Fapp.component.ts

I just updated your targetPrefix method.

  • that is really good way to give answer to someone ! – Dolev Dublon Nov 17 '20 at 08:41
  • IThanks for your feedback. I checked the link but still getting just clicked word but I want the whole string from the clicked word onward back of the string. For example, click on 'test' word then the result string should be 'this is a test' and if I click on 'is' word then the it should return 'this is'. Currently, in the mentioned link, only getting 'clicked word' – Atika.Akmal Nov 17 '20 at 09:12
  • Here you have another example, in this one I added what you are looking for https://stackblitz.com/edit/angular-ivy-xffr3e?file=src%2Fapp%2Fapp.component.ts (I tried to make the code readable enough to make easy to understand my approach) – Eliezer Veras Vargas Nov 17 '20 at 13:15
0

The answer is already given in the link you've provided.

function TargetPrefix(event) {
  let s = window.getSelection();
  let start = event.target.selectionStart; // save cursor position

  s.modify('extend', 'backward', 'word');
  let b = s.toString();

  s.modify('extend', 'forward', 'word');
  let a = s.toString();

  console.log("the clicked word in the string", b + a);

  s.removeAllRanges();  //clear selection
  document.getElementsByTagName('textarea')[0].selectionStart = start; // restore cursor
}
EvgenyV
  • 1,226
  • 14
  • 28