Angular 在文本中获得点击字词
Angular get clicked word in a text
在Angular中,如何获取用户刚刚点击或双击的单词?
我想做的是:用户双击文本中的一个词,然后突出显示该文本。
文本:“这只是一些文本”
the user clicks on the word "just" > I get it in the TS.
我用谷歌搜索了一下,但我找到的唯一信息是 Angular JS 中 10 年前的线程。
提前致谢!
为此,您需要使用 hostListner 来监控 dblclick。请检查以下内容
@HostListener('document:dblclick', ['$event'])
onMouseDown(event) {
let selectedText:any = '';
if (window.getSelection) {
selectedText = window.getSelection().toString();
} else if (document.getSelection) {
selectedText = document.getSelection().toString();
}
console.log(selectedText);
return;
}
我想这对你有帮助
您可以通过从文本中获取所选单词并将其替换为 HTML 标记以突出显示它来实现。
这是工作示例 -
export class AppComponent {
text = "Start editing to see some magic happen";
selectedWord: string;
highlight(event) {
this.selectedWord = window.getSelection().toString();
this.text = this.text.replace(
this.selectedWord,
"<mark>" + this.selectedWord + "</mark>"
);
}
}
在 html 文件中,您需要对文本使用 innerHTML 并像这样在双击事件上调用 highlight() 方法 -
<p [innerHTML]="text" (dblclick)="highlight($event)"></p>
Here 也是一个 stackbiltz 工作示例。
在Angular中,如何获取用户刚刚点击或双击的单词?
我想做的是:用户双击文本中的一个词,然后突出显示该文本。
文本:“这只是一些文本”
the user clicks on the word "just" > I get it in the TS.
我用谷歌搜索了一下,但我找到的唯一信息是 Angular JS 中 10 年前的线程。
提前致谢!
为此,您需要使用 hostListner 来监控 dblclick。请检查以下内容
@HostListener('document:dblclick', ['$event'])
onMouseDown(event) {
let selectedText:any = '';
if (window.getSelection) {
selectedText = window.getSelection().toString();
} else if (document.getSelection) {
selectedText = document.getSelection().toString();
}
console.log(selectedText);
return;
}
我想这对你有帮助
您可以通过从文本中获取所选单词并将其替换为 HTML 标记以突出显示它来实现。
这是工作示例 -
export class AppComponent {
text = "Start editing to see some magic happen";
selectedWord: string;
highlight(event) {
this.selectedWord = window.getSelection().toString();
this.text = this.text.replace(
this.selectedWord,
"<mark>" + this.selectedWord + "</mark>"
);
}
}
在 html 文件中,您需要对文本使用 innerHTML 并像这样在双击事件上调用 highlight() 方法 -
<p [innerHTML]="text" (dblclick)="highlight($event)"></p>
Here 也是一个 stackbiltz 工作示例。