首页 > 解决方案 > 在 Angular 应用程序中获取选定的文本

问题描述

看过一些关于如何在 Angular 项目中获取选定文本的教程后,总是使用以下代码片段,但是当我将它包含在我的组件中时,我得到了错误:

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;
}

第一个红色下划线错误是Object is possibly 'null'。其他三个是Property 'selection' does not exist on type 'Document'

我在这里想念什么?

在此处输入图像描述

标签: htmlangulartypescript

解决方案


尝试使用 @ViewChild 在您的 html 中引用

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

创建范围(https://developer.mozilla.org/en-US/docs/Web/API/Range

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

并获得选择

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

推荐阅读