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.exe
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();
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?