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

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


当前回答

你可以使用Angular模块来实现:

navigator.clipboard.writeText('your text').then().catch(e => console.error(e));

其他回答

对我来说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)”。

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

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);
}

在Angular中做到这一点并保持代码简单的最好方法就是使用这个项目。

https://www.npmjs.com/package/ngx-clipboard

    <fa-icon icon="copy" ngbTooltip="Copy to Clipboard" aria-hidden="true" 
    ngxClipboard [cbContent]="target value here" 
    (cbOnSuccess)="copied($event)"></fa-icon>

以下是@Sangram的回答(以及@Jonathan的评论)的解决方案1:

(支持“不要在angular中使用普通文档”和“如果你没有必要,不要从代码中添加HTML元素……”)

// TS @ViewChild('textarea') textarea: ElementRef; constructor(@Inject(DOCUMENT) private document: Document) {} public copyToClipboard(text): void { console.log(`> copyToClipboard(): copied "${text}"`); this.textarea.nativeElement.value = text; this.textarea.nativeElement.focus(); this.textarea.nativeElement.select(); this.document.execCommand('copy'); } /* CSS */ .textarea-for-clipboard-copy { left: -10000; opacity: 0; position: fixed; top: -10000; } <!-- HTML --> <textarea class="textarea-for-clipboard-copy" #textarea></textarea>