【问题标题】:How to copy textarea content into clipboard in Angular application如何在 Angular 应用程序中将 textarea 内容复制到剪贴板
【发布时间】:2023-03-29 23:26:02
【问题描述】:

我在 Angular 7 应用程序中有一个 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;

这很好用,但文本区域文本仍处于选中状态,我想避免这种情况。将文本复制到剪贴板后,如何取消选择?

谢谢。

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    在选择文本后添加 this.txtConfigFile.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);
    
    }
    

    DEMO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多