javascript - 从文本框中选择文本时触发函数

标签 javascript angular angular8

我使用的是 Angular 8。

我有一个文本框,其中包含一些文本。我希望用户选择文本,选择结束后,我想调用一个以所选文本作为参数的函数。

这是选定的文本框。

enter image description here

现在,当选择 react 时,我想调用一个函数。有什么办法,我可以在 Angular 8 中做到这一点。

最佳答案

假设您的textboxHTML textarea ,您定义 select模板中的事件处理程序如下(此处它指向组件类中的 onTextSelected 方法)。

<textarea #textbox (select)="onTextSelected()">{{ text }}</textarea>

在您的组件类中,您应该获得对 textare 的引用通过使用 @ViewChild 装饰师。然后你需要实现onTextSelected方法。

@ViewChild('textbox', { static: false}) textAreaRef: ElementRef<HTMLTextAreaElement>;

onTextSelected(): void {
  const textArea = this.textAreaRef.nativeElement;
  this.selectedText = textArea.value.substring(textArea.selectionStart, textArea.selectionEnd);
}

请查看以下StackBlitz .

In case you really want to call the method with the selected text, you can change your template as follows and get rid of @ViewChild at the same time.

<textarea #textbox (select)="onTextSelected(textbox.value.substring(textbox.selectionStart, textbox.selectionEnd))">{{ text }}</textarea>

This is is shown in the following StackBlitz

关于javascript - 从文本框中选择文本时触发函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59748209/

相关文章:

javascript - 如何使用loopback api和angularjs检索最新创建的记录

javascript - 输入字段未附加到 td

javascript - 如何在express.js中的两个javascript文件之间传递参数

Angular 8 @ViewChild 翻译

angular - 单击按钮 Angular 时如何更改组件

javascript - 从文件夹 AngularJs 上传图像列表

angular - 寻找一种将全文搜索添加到 firestore 的廉价方法

angular - 从 firebase 中检索所有数据,不包括某些字段

javascript - moment.updateLocale 格式无法分配给 Angular 4 typescript 中类型 'void' 的参数

angular - 为什么 vs19 中的断点在 angular 8 更新后停止工作?