elzoy
elzoy

Reputation: 5435

Angular2 - get selected part of text value

I'd like to create a simple editor to make selected text bolder for example.

There is a textarea with "Super text" value.

Now I select a part of this text (for example "Super"). How to get the selected value?

<textarea (selected)=".."></textarea>

This will call a function every time I select something inside textarea.

<textarea (selected)="view(textarea.value)" #textarea></textarea>

This will print a whole textarea value when I select something. I'd like to print only that part of text, which will be selected. How to do that?

Upvotes: 1

Views: 2451

Answers (1)

mlakhara
mlakhara

Reputation: 245

I see that you are binding your function with the (selected) attribute on texarea. This should be (select) as this is the event which is fired for the selection. But since you say that you are getting your callback executed, I would assume its a typo.

Now to the main question. On the textarea, you have two properties selectionStart and selectionEnd, which as the name suggest are indexes of the position in the value from which the selection starts and ends. So you can get the selected substring by using

textarea.value.substring(textarea.selectionStart, textarea.selectEnd)

You can pass the value of an expression inside your component's functions. Hence, you will do like this

<textarea (select)="view(textarea.selectionStart, textarea.selectEnd)" #textarea></textarea>

Here is a working fiddle for the same. https://jsfiddle.net/h191w4ed/1/

Upvotes: 5

Related Questions