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')
Click an element to copyThe cdkCopyToClipboard directive can be used to easily add copy-on-click functionality to an existing element. The directive selector doubles as an @Input() for the text to be copied.
Select the text or graphics you want to copy, and press Ctrl+C. Each selection appears in the Clipboard, with the latest at the top.
You could implement an Angular2 directive arount the clipboard.js library.
First configure the library into SystemJS:
<script> System.config({ map: { clipboard: 'https://cdn.rawgit.com/zenorocha/clipboard.js/master/dist/clipboard.js' }, packages: { 'app': { defaultExtension: 'js' } } }); (...) </script>
We want to be able to attach clipboard on an element through a directive and provide as parameter the DOM element we want to link with. The value specified into the specified target element will be used to copy its text. Here is a sample of use:
<div> <input #foo/> <button [clipboard]="foo">Copy</button> </div>
The implementation of the directive is the following:
import {Directive,ElementRef,Input,Output,EventEmitter} from 'angular2/core'; import Clipboard from 'clipboard'; @Directive({ selector: '[clipboard]' }) export class ClipboardDirective { clipboard: Clipboard; @Input('clipboard') elt:ElementRef; @Output() clipboardSuccess:EventEmitter<any> = new EventEmitter(); @Output() clipboardError:EventEmitter<any> = new EventEmitter(); constructor(private eltRef:ElementRef) { } ngOnInit() { this.clipboard = new Clipboard(this.eltRef.nativeElement, { target: () => { return this.elt; } }); this.clipboard.on('success', (e) => { this.clipboardSuccess.emit(); }); this.clipboard.on('error', (e) => { this.clipboardError.emit(); }); } ngOnDestroy() { if (this.clipboard) { this.clipboard.destroy(); } } }
See this plunkr for a sample: https://plnkr.co/edit/elyMcP5PX3UP4RkRQUG8?p=preview.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With