Angular 2 - set the selection on the Ref element

I have this choice:

let selection = window.getSelection();

And this elementRef:

@ViewChild('contentEditable') public el: ElementRef;

And, for example, this text is inside the contenteditable elementRef:

This is text

Where I selected 'some', then lost the selection, but saved it in the selection property using getSelection (). How do I set it to elementRef?

+4
source share
1 answer

I misled input with contentEditable. With contentEditable, you need to use a range to get the selection and set the selection.

To get a choice:

let range = document.createRange();
range = window.getSelection().getRangeAt(0);
this.rangeClone = range.cloneRange();

A combination of Selection and Range objects is used in Javascript. For more information, read the docs:

Selection

Range

To set a selection:

this.el.nativeElement.focus();
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(this.rangeClone);

This.el looks like this:

@ViewChild('contentEditable') public el: ElementRef;
+1

Source: https://habr.com/ru/post/1688404/


All Articles