Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy to clipboard in Angular 2 Typescript?

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') 
like image 228
Andris Krauze Avatar asked Mar 31 '16 08:03

Andris Krauze


People also ask

How to copy text in angular material?

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.

How do I copy text to clipboard?

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.


1 Answers

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.

like image 79
Thierry Templier Avatar answered Sep 26 '22 18:09

Thierry Templier