How do I copy to clipboard in Angular 2 Typescript

2019-01-12 02:11发布

Is there a way to copy text in clipboard (multi-browser) in Angular2 Typescript framework?

I find only sources of using Javascript, e.g.

document.execCommand('copy')

9条回答
太酷不给撩
2楼-- · 2019-01-12 03:00

Here is a simple code in case your text is not inside an input or textarea, but a div, or any other HTMLElement:

window.getSelection().selectAllChildren(document.getElementById('yourID');
document.execCommand("Copy");

I was unable to use the select() command because it wasn't recognized by Angular. Hope this helps someone!

查看更多
劳资没心,怎么记你
3楼-- · 2019-01-12 03:01

Here is a way to achieve this without any external dependency or creating fake elements, only by using Clipboard API:

import { DOCUMENT } from '@angular/common';
import { Directive, EventEmitter, HostListener, Inject, Input, Output } from '@angular/core';

@Directive({
  selector: '[myClipboard]'
})
export class ClipboardDirective {

  @Input() myClipboard: string;
  @Output() myClipboardSuccess = new EventEmitter<ClipboardEvent>();

  constructor(@Inject(DOCUMENT) private document: Document) {}

  @HostListener('click')
  onClick() {
    this.document.addEventListener('copy', this.handler);
    this.document.execCommand('copy');
  }

  private handler = (e: ClipboardEvent) => {
    e.clipboardData.setData('text/plain', this.myClipboard);
    e.preventDefault();
    this.myClipboardSuccess.emit(e);
    this.document.removeEventListener('copy', this.handler);
  }

}

Can I use Clipboard API?

查看更多
冷血范
4楼-- · 2019-01-12 03:02

The code that you mentioned is the right way to do it and it can be done in Angular 2+ too.

I don't know what you accualy need to do, but if you, for example, have an input and a button:

(.html file)

<input id='inputId'></input>
<button (click)="copyToClipboard()'>click me</button>

then all you need to do is:

(.ts file)

public copyToClipboard(): void {
  const inputElement = document.getElementById('inputId');
  (<any>inputElement).select();
  document.execCommand('copy');
  inputElement.blur();
}
查看更多
登录 后发表回答