我使用的是 Angular 8。
我有一个文本框,其中包含一些文本。我希望用户选择文本,选择结束后,我想调用一个以所选文本作为参数的函数。
这是选定的文本框。
现在,当选择 react 时,我想调用一个函数。有什么办法,我可以在 Angular 8 中做到这一点。
最佳答案
假设您的textbox
是 HTML 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/