Javascript Angular 4 - 将文本复制到剪贴板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45768583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:12:30  来源:igfitidea点击:

Angular 4 - Copy text to clipboard

javascriptangular

提问by kayasa

I have a clickable icon on the page. On click on this icon, I would like to construct some text and copy that in the clipboard

我在页面上有一个可点击的图标。单击此图标,我想构建一些文本并将其复制到剪贴板中

<td><img src='./assets/Copy.gif' (click)="copyToClipboard()"  /></td> 

and in the Component

并在组件中

  copyToClipboard() {
     this.textToCopy = this.text1 + this.text2 + this.text3;  
     this.toastr.info('Copied to Clipboard');
  }

I have looked at https://www.npmjs.com/package/ngx-clipboard. However, this package requires to refer to an input element and copy the text from that input element. In my use case, the text needs to be dynamically created and then added to clipboard.

我看过https://www.npmjs.com/package/ngx-clipboard。但是,此包需要引用输入元素并从该输入元素复制文本。在我的用例中,文本需要动态创建,然后添加到剪贴板。

Can I use ngx-clipboard to copy to clipboard or is there be another package that would enable me to achieve this?

我可以使用 ngx-clipboard 复制到剪贴板还是有另一个包可以让我实现这一目标?

采纳答案by Faisal

You need to use ngxClipboarddirective with your image. This is how you need to use it to solve your issue:

您需要对ngxClipboard图像使用指令。这是您需要如何使用它来解决您的问题:

<td>
    <img src='./assets/Copy.gif' (click)="copyToClipboard()" ngxClipboard [cbContent]="textToCopy" />
</td> 

Remember to add ClipboardModulein your app module. Example code below:

记得ClipboardModule在你的应用模块中添加。示例代码如下:

import { ClipboardModule } from 'ngx-clipboard';

@NgModule({
  imports: [
    // Other Imports
    ClipboardModule
  ],
  // Other code
})
export class AppModule { }

回答by Gangadhar JANNU

User interaction is mandatory for executing document.execCommand, which is used for copying text to the clipboard.

用户交互对于执行是必需的document.execCommand,它用于将文本复制到剪贴板。

See my other answer.

请参阅我的另一个答案

If you don't want to use any third party library, you could use below snippet for copying text to the clipboard.

如果您不想使用任何第三方库,您可以使用下面的代码片段将文本复制到剪贴板。

function copyTextToClipboard(text) {
  var txtArea = document.createElement("textarea");
  txtArea.id = 'txt';
  txtArea.style.position = 'fixed';
  txtArea.style.top = '0';
  txtArea.style.left = '0';
  txtArea.style.opacity = '0';
  txtArea.value = text;
  document.body.appendChild(txtArea);
  txtArea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
    if (successful) {
      return true;
    }
  } catch (err) {
    console.log('Oops, unable to copy');
  } finally {
    document.body.removeChild(txtArea);
  }
  return false;
}

Change copyToClipboardfunction as below to call the copyTextToClipboard function

更改copyToClipboard如下函数以调用 copyTextToClipboard 函数

copyToClipboard() {
    this.textToCopy = this.text1 + this.text2 + this.text3;
    var result = this.copyTextToClipboard(this.textToCopy);
    if (result) {
        this.toastr.info('Copied to Clipboard');
    }
}

回答by Zahidul Islam Ruhel

This is the easiest way to copy to clipboard.

这是复制到剪贴板的最简单方法。

In your template

在您的模板中

<button (click)="copyToClipboard(sharableLink)">Copy link</button>
<input type="text" value="This is the value to copy" #sharableLink>

In component

在组件中

copyToClipboard(element) {
    element.select();
    document.execCommand('copy');
    this.toaster('success', 'Success!', 'Link copied to clipboard.');
  }

回答by velval

Here another quick and dirty option without the need of third-party libraries or modules. Taken from here

这是另一个不需要第三方库或模块的快速而肮脏的选择。取自这里

In your template

在您的模板中

<a class="accent" (click)="copyLink(textToCopy)">{{textToCopy}}</a>

And in your component

在你的组件中

copyLink(text:string) {
        const event = (e: ClipboardEvent) => {
            e.clipboardData.setData('text/plain', text);
            e.preventDefault();
            // ...('copy', e), as event is outside scope
            document.removeEventListener('copy', e);
        }
        document.addEventListener('copy', event);
        document.execCommand('copy');
    }

回答by dilantha111

ngx-clipboard now doesn't require you to use input element. Now it's more straight forward and provide several ways of doing this. One way to do is simply use ClipboardService. From three, documentation

ngx-clipboard 现在不需要你使用 input 元素。现在它更直接,并提供了几种方法来做到这一点。一种方法是简单地使用 ClipboardService。从三、文档

import { ClipboardService } from 'ngx-clipboard'

constructor(private _clipboardService: ClipboardService){
...
}
copy(text: string){
  this._clipboardService.copyFromContent(text)
}

But in my case this didn't work. And I got some warnings at the compile time in angular that peer dependencies are not met. Since I was using Angular 4 these warning I expected. But there's a simple way to do this with @ViewChild if the above solution doesn't work for you.

但就我而言,这不起作用。我在编译时收到了一些警告,指出不满足对等依赖项。因为我使用的是 Angular 4,所以我预料到了这些警告。但是,如果上述解决方案对您不起作用,则有一种简单的方法可以使用 @ViewChild 执行此操作。

in your html :

在你的 html 中:

<textarea name="copyText" #copyText id="" style="opacity: 0;height: 0;"></textarea>

And in Component :

在 Component 中:

@ViewChild('copyText', { read: ElementRef }) copyText: ElementRef;

copyText() {
    const element = this.copyText.nativeElement;
    element.value = 'some text';
    element.focus();
    element.select();
    document.execCommand('copy');
}

This is just simple vanilla javascript approach with Angular's @ViewChild

这只是带有 Angular 的 @ViewChild 的简单香草 javascript 方法

回答by Philo

The problem (later highlighted by the OP) of the approved answer, using NgxClipboard, is that the content could not be set dynamically.

使用 NgxClipboard 的已批准答案的问题(稍后由 OP 突出显示)是无法动态设置内容。

Using a (click) event listener doesn't work, because it is triggered afterngxClipboard execution.

使用 (click) 事件侦听器不起作用,因为它是ngxClipboard 执行触发的。

So, simply define [cbContent] with an @Input getter, and forget about the (click) event:

因此,只需使用 @Input getter 定义 [cbContent],而忘记 (click) 事件:

In the template:

在模板中:

<button ngxClipboard [cbContent]="foo">Click me</button>

In the component:

在组件中:

@Input()
get foo() {
    // Dynamic generation of the text to put in the clipboard:
    return this.text1 + this.text2 + this.text3
}