Angular 5 - Copy to clipboard

后端 未结 11 1083
旧巷少年郎
旧巷少年郎 2020-11-30 18:26

I am trying to implement an icon that when clicked will save a variable to the user\'s clipboard. I have currently tried several libraries and none of them have been able to

相关标签:
11条回答
  • 2020-11-30 19:03

    The best way to do this in Angular and keep the code simple is to use this project.

    https://www.npmjs.com/package/ngx-clipboard

        <fa-icon icon="copy" ngbTooltip="Copy to Clipboard" aria-hidden="true" 
        ngxClipboard [cbContent]="target value here" 
        (cbOnSuccess)="copied($event)"></fa-icon>
    
    0 讨论(0)
  • 2020-11-30 19:05

    First suggested solution works, we just need to change

    selBox.value = val;
    

    To

    selBox.innerText = val;
    

    i.e.,

    HTML:

    <button (click)="copyMessage('This goes to Clipboard')" value="click to copy" >Copy this</button>
    

    .ts file:

    copyMessage(val: string){
        const selBox = document.createElement('textarea');
        selBox.style.position = 'fixed';
        selBox.style.left = '0';
        selBox.style.top = '0';
        selBox.style.opacity = '0';
        selBox.innerText = val;
        document.body.appendChild(selBox);
        selBox.focus();
        selBox.select();
        document.execCommand('copy');
        document.body.removeChild(selBox);
      }
    
    0 讨论(0)
  • 2020-11-30 19:07

    Modified version of jockeisorby's answer that fixes the event handler not being properly removed.

    copyToClipboard(item): void {
        let listener = (e: ClipboardEvent) => {
            e.clipboardData.setData('text/plain', (item));
            e.preventDefault();
        };
    
        document.addEventListener('copy', listener);
        document.execCommand('copy');
        document.removeEventListener('copy', listener);
    }
    
    0 讨论(0)
  • 2020-11-30 19:15

    Use navigator.clipboard.writeText to copy the content to clipboard

    navigator.clipboard.writeText(content).then().catch(e => console.error(e));
    
    0 讨论(0)
  • 2020-11-30 19:16

    I know this has already been highly voted in here by now, but I'd rather go for a custom directive approach and rely on the ClipboardEvent as @jockeisorby suggested, while also making sure the listener is correctly removed (same function needs to be provided for both the add and remove event listeners)

    stackblitz demo

    import { Directive, Input, Output, EventEmitter, HostListener } from "@angular/core";
    
    @Directive({ selector: '[copy-clipboard]' })
    export class CopyClipboardDirective {
    
      @Input("copy-clipboard")
      public payload: string;
    
      @Output("copied")
      public copied: EventEmitter<string> = new EventEmitter<string>();
    
      @HostListener("click", ["$event"])
      public onClick(event: MouseEvent): void {
    
        event.preventDefault();
        if (!this.payload)
          return;
    
        let listener = (e: ClipboardEvent) => {
          let clipboard = e.clipboardData || window["clipboardData"];
          clipboard.setData("text", this.payload.toString());
          e.preventDefault();
    
          this.copied.emit(this.payload);
        };
    
        document.addEventListener("copy", listener, false)
        document.execCommand("copy");
        document.removeEventListener("copy", listener, false);
      }
    }
    

    and then use it as such

    <a role="button" [copy-clipboard]="'some stuff'" (copied)="notify($event)">
      <i class="fa fa-clipboard"></i>
      Copy
    </a>
    
    public notify(payload: string) {
       // Might want to notify the user that something has been pushed to the clipboard
       console.info(`'${payload}' has been copied to clipboard`);
    }
    

    Note: notice the window["clipboardData"] is needed for IE as it does not understand e.clipboardData

    0 讨论(0)
提交回复
热议问题