'Angular 5 - Copy to clipboard

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 do so.

How do I properly copy a variable to the user's clipboard in Angular 5?



Solution 1:[1]

Solution 1: Copy any text

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.value = val;
    document.body.appendChild(selBox);
    selBox.focus();
    selBox.select();
    document.execCommand('copy');
    document.body.removeChild(selBox);
  }

Solution 2: Copy from a TextBox

HTML

 <input type="text" value="User input Text to copy" #userinput>
      <button (click)="copyInputMessage(userinput)" value="click to copy" >Copy from Textbox</button>

.ts file

    /* To copy Text from Textbox */
  copyInputMessage(inputElement){
    inputElement.select();
    document.execCommand('copy');
    inputElement.setSelectionRange(0, 0);
  }

Demo Here


Solution 3: Import a 3rd party directive ngx-clipboard

<button class="btn btn-default" type="button" ngxClipboard [cbContent]="Text to be copied">copy</button>

Solution 4: Custom Directive

If you prefer using a custom directive, Check Dan Dohotaru's answer which is an elegant solution implemented using ClipboardEvent.


Solution 5: Angular Material

Angular material 9 + users can utilize the built-in clipboard feature to copy text. There are a few more customization available such as limiting the number of attempts to copy data.

Solution 2:[2]

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

Solution 3:[3]

I think this is a much more cleaner solution when copying text:

copyToClipboard(item) {
    document.addEventListener('copy', (e: ClipboardEvent) => {
      e.clipboardData.setData('text/plain', (item));
      e.preventDefault();
      document.removeEventListener('copy', null);
    });
    document.execCommand('copy');
  }

And then just call copyToClipboard on click event in html. (click)="copyToClipboard('texttocopy')".

Solution 4:[4]

As of Angular Material v9, it now has a clipboard CDK

Clipboard | Angular Material

It can be used as simply as

<button [cdkCopyToClipboard]="This goes to Clipboard">Copy this</button>

Solution 5:[5]

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);
}

Solution 6:[6]

Copy using angular cdk,

Module.ts

import {ClipboardModule} from '@angular/cdk/clipboard';

Programmatically copy a string: MyComponent.ts,

class MyComponent {
  constructor(private clipboard: Clipboard) {}

  copyHeroName() {
    this.clipboard.copy('Alphonso');
  }
}

Click an element to copy via HTML:

<button [cdkCopyToClipboard]="longText" [cdkCopyToClipboardAttempts]="2">Copy text</button>

Reference: https://material.angular.io/cdk/clipboard/overview

Solution 7:[7]

You can achieve this using Angular modules:

navigator.clipboard.writeText('your text').then().catch(e => console.error(e));

Solution 8:[8]

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

navigator.clipboard.writeText(content).then().catch(e => console.error(e));

Solution 9:[9]

Below method can be used for copying the message:-

export function copyTextAreaToClipBoard(message: string) {
  const cleanText = message.replace(/<\/?[^>]+(>|$)/g, '');
  const x = document.createElement('TEXTAREA') as HTMLTextAreaElement;
  x.value = cleanText;
  document.body.appendChild(x);
  x.select();
  document.execCommand('copy');
  document.body.removeChild(x);
}

Solution 10:[10]

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>

Solution 11:[11]

// for copy the text
import { Clipboard } from "@angular/cdk/clipboard"; // first import this in .ts
 constructor(
    public clipboard: Clipboard
  ) { }   
 <button class="btn btn-success btn-block"(click) = "onCopy('some text')" > Copy< /button>

 onCopy(value) {
     this.clipboard.copy(value);
    }


 // for paste the copied text on button click :here is code
    
    <button class="btn btn-success btn-block"(click) = "onpaste()" > Paste < /button>
    
    onpaste() {
      navigator['clipboard'].readText().then(clipText => {
        console.log(clipText);
      });
    }

Solution 12:[12]

For me document.execCommand('copy') was giving deprecated warning and the data I need to copy was inside <div> as textNode rather than <input> or <textarea>.

This is how I did it in Angular 7 (inspired by answers of @Anantharaman and @Codemaker):

<div id="myDiv"> &lt &nbsp This is the text to copy. &nbsp &gt </div>
<button (click)="copyToClipboard()" class="copy-btn"></button>
 copyToClipboard() {
    const content = (document.getElementById('myDiv') as HTMLElement).innerText;
    navigator['clipboard'].writeText(content).then().catch(e => console.error(e));

  }
}

Definitely not the best way, but it serves the purpose.

Solution 13:[13]

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);
  }

Solution 14:[14]

Found the simplest solution for myself with pure Angular and ViewChild.

import { Component, ViewChild } from '@angular/core';

@Component({
  selector: 'cbtest',
  template: `
    <input type="text" #inp/>
    <input type="button" (click)="copy ()" value="copy now"/>`
})

export class CbTestComponent
{
  @ViewChild ("inp") inp : any;

  copy ()
  {
    // this.inp.nativeElement.value = "blabla";  // you can set a value manually too

    this.inp.nativeElement.select ();   // select
    document.execCommand ("copy");      // copy
    this.inp.nativeElement.blur ();     // unselect
  }
}

Solution 15:[15]

Following Solution 1 of @Sangram's answer (and the comment from @Jonathan):

(In favor of "do not use plain document in angular" and "do not add HTML elements from code if you don't have to...)

// TS

@ViewChild('textarea') textarea: ElementRef;

constructor(@Inject(DOCUMENT) private document: Document) {}

public copyToClipboard(text): void {
  console.log(`> copyToClipboard(): copied "${text}"`);
  this.textarea.nativeElement.value = text;
  this.textarea.nativeElement.focus();
  this.textarea.nativeElement.select();
  this.document.execCommand('copy');
}
/* CSS */
.textarea-for-clipboard-copy {
  left: -10000;
  opacity: 0;
  position: fixed;
  top: -10000;
}
<!-- HTML -->
<textarea class="textarea-for-clipboard-copy" #textarea></textarea>

Solution 16:[16]

It's simple bro

in .html file

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

in .ts file

copyMessage(text: string) {
  navigator.clipboard.writeText(text).then().catch(e => console.log(e));
}

Solution 17:[17]

copyCurl(val: string){
    navigator.clipboard.writeText(val).then( () => {
      this.toastr.success('Text copied to clipboard');
    }).catch( () => {
      this.toastr.error('Failed to copy to clipboard');
    });
}