简体   繁体   中英

How to copy textarea content into clipboard in Angular application

I have a textarea in an Angular 7 application and I need to copy its content to the clipboard upon clicking on a button. I use this code on the button's click handler:

if (this.txtConfigFile) {
    // Select textarea text
    this.txtConfigFile.nativeElement.select();

    // Copy to the clipboard
    document.execCommand("copy");

    // The following lines (in theory) unselect the text (DON'T WORK)
    this.txtConfigFile.nativeElement.value = this.txtConfigFile.nativeElement.value;
    this.txtConfigFile.nativeElement.blur();
}

NOTE: txtConfigFile is the reference to the textarea element, which I get using @ViewChild in the component's declaration:

@ViewChild('txtConfigFile') txtConfigFile: ElementRef;

This works fine, but the text-area text remains selected, and I'd like to avoid this. After copying the text to the clipboard, how can I unselect it?

Thanks.

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){
    let 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>

Instead add this.txtConfigFile.nativeElement.setSelectionRange(0, 0); after selecting your text to deselect it :

 if (this.txtConfigFile) {
  // Select textarea text
  this.txtConfigFile.nativeElement.select();

  // Copy to the clipboard
  document.execCommand("copy");

  // Deselect selected textarea
  this.txtConfigFile.nativeElement.setSelectionRange(0, 0);

}

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM