我试图实现一个图标,当点击将保存一个变量到用户的剪贴板。我目前已经尝试了几个库,没有一个能够做到这一点。

在Angular 5中,如何正确地将一个变量复制到用户的剪贴板中?


当前回答

以下方法可用于复制消息:-

export function copyTextAreaToClipBoard(message: string) {
  const cleanText = message.replace(/<\/?[^>]+(>|$)/g, '');
  const x = document.createElement('TEXTAREA') as HTMLTextAreaElement;
  x.value = cleanText;
  document.body.appendChild(x);
  x.select();
  document.execCommand('copy');
  document.body.removeChild(x);
}

其他回答

很简单,兄弟

在.html文件

<button (click)="copyMessage('This goes to Clipboard')" value="click to copy" >Copy this</button>

在.ts文件

copyMessage(text: string) {
  navigator.clipboard.writeText(text).then().catch(e => console.log(e));
}

用纯Angular和ViewChild为自己找到了最简单的解决方案。

import { Component, ViewChild } from '@angular/core';

@Component({
  selector: 'cbtest',
  template: `
    <input type="text" #inp/>
    <input type="button" (click)="copy ()" value="copy now"/>`
})

export class CbTestComponent
{
  @ViewChild ("inp") inp : any;

  copy ()
  {
    // this.inp.nativeElement.value = "blabla";  // you can set a value manually too

    this.inp.nativeElement.select ();   // select
    document.execCommand ("copy");      // copy
    this.inp.nativeElement.blur ();     // unselect
  }
}

从Angular Material v9开始,它现在有了一个剪贴板CDK

剪贴板|角材料

它可以简单地使用

<button [cdkCopyToClipboard]="This goes to Clipboard">Copy this</button>

对我来说document.execCommand('copy')给出了弃用警告,我需要复制的数据是在<div>作为textNode,而不是<input>或<textarea>。

这是我在Angular 7中的做法(灵感来自@Anantharaman和@Codemaker的回答):

<div id="myDiv"> &lt &nbsp This is the text to copy. &nbsp &gt </div>
<button (click)="copyToClipboard()" class="copy-btn"></button>
 copyToClipboard() {
    const content = (document.getElementById('myDiv') as HTMLElement).innerText;
    navigator['clipboard'].writeText(content).then().catch(e => console.error(e));

  }
}

绝对不是最好的方法,但它达到了目的。

我认为在复制文本时,这是一个更干净的解决方案:

copyToClipboard(item) {
    document.addEventListener('copy', (e: ClipboardEvent) => {
      e.clipboardData.setData('text/plain', (item));
      e.preventDefault();
      document.removeEventListener('copy', null);
    });
    document.execCommand('copy');
  }

然后在html中的click事件上调用copyToClipboard。(点击)= " copyToClipboard (texttocopy)”。