0

I have a method in Angular2 that generates a sharable link which is something like a requestPath. On button click, I need to copy this requestPath to clipboard. How to achieve that?

I came across multiple copy-to-clipboard solutions here but nothing meets my need. I do not have a textArea or any input element to copy from. Just a simple string variable needed to be copied onClick

The html I have is:

<td class="submitBtnCell">
    <button class="btn" (click)="createSharableLink()">Share</button>
</td>

and method:

createSharableLink(){
    let requestPath = this.prepareRequestPathForVideos("shared");
    alert(requestPath); // need to copy this request path to clipboard       
}
roger_that
  • 9,493
  • 18
  • 66
  • 102

2 Answers2

2

Here is a snippet I've used in one of my previous projects which allows you to copy things to your clipboard.

Also mentioned by Carsten below.

// Copy Element Into Clipboard [ Can use "$(val).text()" as Argument ]
function copyToClipboard(element) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val(element).select();
    document.execCommand("copy");
    $temp.remove();
}

It appends a hidden <input> to the body of the page, adds your element to it, selects the text and uses execCommand to copy the selected text.

Using your code, here's an example:

<td class="submitBtnCell">
    <button class="btn" (click)="createSharableLink()">Share</button>
</td>

createSharableLink(){
    let requestPath = this.prepareRequestPathForVideos("shared");
    //alert(requestPath); // need to copy this request path to clipboard   
    copyToClipboard(requestPath);  
}

Reference: https://angular.io/guide/rx-library#naming-conventions-for-observables

StackOverflow Link: angular2 style guide - property with dollar sign?

Because Angular applications are mostly written in TypeScript, you will typically know when a variable is an observable. Although the Angular framework does not enforce a naming convention for observables, you will often see observables named with a trailing “$” sign.

This can be useful when scanning through code and looking for observable values. Also, if you want a property to store the most recent value from an observable, it can be convenient to simply use the same name with or without the “$”.

Alex
  • 2,164
  • 1
  • 9
  • 27
0

For security reasons you cannot directly access the clipboard. You can create a hidden input element, set the text in there and trigger the copy functionality from it.

Carsten
  • 4,005
  • 21
  • 28