html - 在 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'
。
我在这里想念什么?
解决方案
尝试使用 @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();
推荐阅读
- matlab - 在 MATLAB 中消除连续区域(泛化:之间有零的区域)
- c# - DDD 解决方案结构
- javascript - 尝试自动化 jQuery 点击事件并显示内容
- c - 如何在 C 中将 char 附加到字符串中动态分配内存?
- javascript - 使用 AJAX 预填充 Django Select 表单
- python - 如何使用 Tensorflow 估计器对保存的模型进行评分?
- python-3.x - 对象不可迭代。我怎样才能使这个代码工作
- laravel - Laravel 身份验证生命周期
- aem - AEM 在 DAM 中搜索文件
- node.js - 没有 SSH 的情况下,像“Localtunnel”这样的隧道服务如何工作?