Javascript 如何在Angular应用程序中将textarea内容复制到剪贴板
我在Angular 7应用程序中有一个Javascript 如何在Angular应用程序中将textarea内容复制到剪贴板,javascript,angular,Javascript,Angular,我在Angular 7应用程序中有一个textarea,我需要单击按钮将其内容复制到剪贴板。我在按钮的单击处理程序上使用以下代码: if (this.txtConfigFile) { // Select textarea text this.txtConfigFile.nativeElement.select(); // Copy to the clipboard document.execCommand("copy"); // The followi
textarea
,我需要单击按钮将其内容复制到剪贴板。我在按钮的单击处理程序上使用以下代码:
if (this.txtConfigFile) {
// Select textarea text
this.txtConfigFile.nativeElement.select();
// Copy to the clipboard
document.execCommand("copy");
// The following lines (in theory) unselect the text (DON'T WORK)
this.txtConfigFile.nativeElement.value = this.txtConfigFile.nativeElement.value;
this.txtConfigFile.nativeElement.blur();
}
注意:txtConfigFile
是对textarea元素的引用,我使用组件声明中的@ViewChild
获取该元素:
@ViewChild('txtConfigFile') txtConfigFile: ElementRef;
这很好,但是文本区域文本仍然处于选中状态,我希望避免这种情况。将文本复制到剪贴板后,如何取消选中它
谢谢。改为添加
此.txtconfifile.nativeElement.setSelectionRange(0,0)代码>选择要取消选择的文本后:
if (this.txtConfigFile) {
// Select textarea text
this.txtConfigFile.nativeElement.select();
// Copy to the clipboard
document.execCommand("copy");
// Deselect selected textarea
this.txtConfigFile.nativeElement.setSelectionRange(0, 0);
}