[Fixed] Angular 4 – Copy text to clipboard


I have a clickable icon on the page. On click on this icon, I would like to construct some text and copy that in the clipboard

<td><img src='./assets/Copy.gif' (click)="copyToClipboard()"  /></td> 

and in the Component

  copyToClipboard() {
     this.textToCopy = this.text1 + this.text2 + this.text3;  
     this.toastr.info('Copied to Clipboard');

I have looked at https://www.npmjs.com/package/ngx-clipboard. However, this package requires to refer to an input element and copy the text from that input element. In my use case, the text needs to be dynamically created and then added to clipboard.

Can I use ngx-clipboard to copy to clipboard or is there be another package that would enable me to achieve this?


You need to use ngxClipboard directive with your image. This is how you need to use it to solve your issue:

    <img src='./assets/Copy.gif' (click)="copyToClipboard()" ngxClipboard [cbContent]="textToCopy" />

Remember to add ClipboardModule in your app module. Example code below:

import { ClipboardModule } from 'ngx-clipboard';

  imports: [
    // Other Imports
  // Other code
export class AppModule { }

Leave a Reply

(*) Required, Your email will not be published