0

I am able to copy data to the clipboard using a button press as seen below. But how can use the same behavior to get data from the clipboard? The paste event only works when I click into an input field or text area. I need it to be able to work using a button.

I tried using window.clipboardData but it doesn't recognize it. Is there a way I can fire the Paste event through a button press?

 Copy(val) {
    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);
     this.icon = 'checkmark';
     this.copyButtonText = 'Copied!';
     this.tooltip = true;
 }

my html

   <button #copyButton [icon]='this.icon' (click)="Copy(this.text)">{{copyButtonText}}</button>    
   <textarea [disabled]="true"> {{this.text}} </textarea>
Terrance Jackson
  • 606
  • 3
  • 13
  • 40

1 Answers1

2

The best way to achieve this is to use window selection handler.

let clipboardContent:string = "" //the clipboard content variable

window.addEventListener('copy', (e:ClipboardEvent) => {
  clipboardContent = window.getSelection().toString();
  //everytime someone copies some thing its text content 
  //is available within the clipboardContent variable
});

//now for the button press event you have the clipboard data
buttonElement.addEventListener('click', () => {
  //paste your content
  textareaElement.value = clipboardContent;
});
Max Gaurav
  • 1,835
  • 2
  • 13
  • 26