How do I copy to clipboard in Angular 2 Typescript?

前端 未结 10 1070
-上瘾入骨i
-上瘾入骨i 2020-12-03 06:45

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         


        
10条回答
  •  我在风中等你
    2020-12-03 07:38

    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?

提交回复
热议问题