HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptangularCriticalCanonical

Angular 5 - Copy to clipboard

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
angularcopyclipboard

Problem

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

Solution 1: Copy any text

HTML

Copy this


.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


      Copy from Textbox


.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

copy


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.

Code Snippets

<button (click)="copyMessage('This goes to Clipboard')" value="click to copy" >Copy this</button>
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);
  }
<input type="text" value="User input Text to copy" #userinput>
      <button (click)="copyInputMessage(userinput)" value="click to copy" >Copy from Textbox</button>
/* To copy Text from Textbox */
  copyInputMessage(inputElement){
    inputElement.select();
    document.execCommand('copy');
    inputElement.setSelectionRange(0, 0);
  }
<button class="btn btn-default" type="button" ngxClipboard [cbContent]="Text to be copied">copy</button>

Context

Stack Overflow Q#49102724, score: 381

Revisions (0)

No revisions yet.