0

I have a list of text entries followed by a button:

<li *ngFor="let match of matches; let i = index">
  {{ match}} <button (click)="select(i)">Copy</button>
</li>

and I would like to copy the text to the clipboard when the user cliked the button.

  public select(index:any){
    document.execCommand("copy");       
  }

This does work, however, I somehow have to select the text of the corresponding text first. How can I do this in Angular2?

user66875
  • 2,772
  • 3
  • 29
  • 55
  • Possible duplicate of [Selecting text in an element (akin to highlighting with your mouse)](http://stackoverflow.com/questions/985272/selecting-text-in-an-element-akin-to-highlighting-with-your-mouse) – YounesM Apr 05 '17 at 08:08
  • Possible duplicate of [How can I copy to clipboard in HTML5 without using flash?](http://stackoverflow.com/questions/26336138/how-can-i-copy-to-clipboard-in-html5-without-using-flash) – n00dl3 Apr 05 '17 at 08:12
  • The proposed links all require jquery or some dom selection to select the actual text. My question is how to do that in angular2. – user66875 Apr 05 '17 at 08:24

2 Answers2

2

See the answers in How can I copy to clipboard in HTML5 without using flash?

The question is old, but the premise is the same. The standard forbids you to use the user's clipboard without express consent of what is going to be copied. You can't skip the select process. The implementation varies from browser to browser but it's pretty much the same all around.

Read more: https://developers.google.com/web/updates/2015/04/cut-and-copy-commands

Community
  • 1
  • 1
fixmycode
  • 8,220
  • 2
  • 28
  • 43
0

I have used angular2-clipboard. It works with angular version 2.0.0 and up.I uses clipboard.js. For more information, refer to their documentation.

Dependencies

  • Angular ~2.0.s0

  • clipboard.js

Usage is as follows :

In component.html file

<button ngIIclipboard [cbContent]="textToCopy" (cbOnSuccess)="onSuccess($event)" class="bm-action-btn clickToCopyPolicy">Click to copy text</button>

In component.ts file

textToCopy = "xyz";
monica
  • 1,454
  • 14
  • 28