Search code examples
angularclipboard.js

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')

Solution

  • 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.