roger_that
roger_that

Reputation: 9791

Copy a String to clipboard in Angular 2

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       
}

Upvotes: 0

Views: 2559

Answers (2)

Alex
Alex

Reputation: 2232

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 “$”.

Upvotes: 2

Carsten
Carsten

Reputation: 4208

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.

Upvotes: 0

Related Questions