Search code examples
angularselectioncontenteditabletextselection

angular 2 - set a selection on an elementRef


I have this selection:

let selection = window.getSelection();

And this elementRef:

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

And for example this text is inside the contenteditable elementRef:

This is some text

Where i selected 'some' then lost the selection but saved it in the selection property with getSelection(). How do i set it back on the elementRef?


Solution

  • I was confusing input with contentEditable. With contentEditable you need to use a range to get the selection and set the selection.

    To get the selection:

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

    This uses a combination of the Selection and Range objects in Javascript. For more info, read the docs:

    Selection

    Range

    To set the 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;