Getting the selected text in an Angular app

Viewed 257

Having looked at a few tutorials on how to get the selected text in an Angular project, the following snippet is always used, but when I include it in my component, I get errors:

getSelection() {

    let text = "";

    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }

    return text;
}

The first red underline error is Object is possibly 'null'. The other three are Property 'selection' does not exist on type 'Document'.

What am I missing here?

enter image description here

1 Answers

Try to reference in your html using @ViewChild

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

create range (https://developer.mozilla.org/en-US/docs/Web/API/Range)

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

And get selection

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