I am trying to implement an icon that when clicked will save a variable to the user's clipboard. I have currently tried several libraries and none of them have been able to do so.
How do I properly copy a variable to the user's clipboard in Angular 5?
This question is related to
angular
typescript
angular5
Use navigator.clipboard.writeText
to copy the content to clipboard
navigator.clipboard.writeText(content).then().catch(e => console.error(e));
Modified version of jockeisorby's answer that fixes the event handler not being properly removed.
copyToClipboard(item): void {
let listener = (e: ClipboardEvent) => {
e.clipboardData.setData('text/plain', (item));
e.preventDefault();
};
document.addEventListener('copy', listener);
document.execCommand('copy');
document.removeEventListener('copy', listener);
}
First suggested solution works, we just need to change
selBox.value = val;
To
selBox.innerText = val;
i.e.,
HTML:
<button (click)="copyMessage('This goes to Clipboard')" value="click to copy" >Copy this</button>
.ts file:
copyMessage(val: string){
const selBox = document.createElement('textarea');
selBox.style.position = 'fixed';
selBox.style.left = '0';
selBox.style.top = '0';
selBox.style.opacity = '0';
selBox.innerText = val;
document.body.appendChild(selBox);
selBox.focus();
selBox.select();
document.execCommand('copy');
document.body.removeChild(selBox);
}
Below method can be used for copying the message:-
export function copyTextAreaToClipBoard(message: string) {
const cleanText = message.replace(/<\/?[^>]+(>|$)/g, '');
const x = document.createElement('TEXTAREA') as HTMLTextAreaElement;
x.value = cleanText;
document.body.appendChild(x);
x.select();
document.execCommand('copy');
document.body.removeChild(x);
}
I think this is a much more cleaner solution when copying text:
copyToClipboard(item) {
document.addEventListener('copy', (e: ClipboardEvent) => {
e.clipboardData.setData('text/plain', (item));
e.preventDefault();
document.removeEventListener('copy', null);
});
document.execCommand('copy');
}
And then just call copyToClipboard on click event in html. (click)="copyToClipboard('texttocopy')"
Copy using angular cdk,
Module.ts
import {ClipboardModule} from '@angular/cdk/clipboard';
Programmatically copy a string: MyComponent.ts,
class MyComponent {
constructor(private clipboard: Clipboard) {}
copyHeroName() {
this.clipboard.copy('Alphonso');
}
}
Click an element to copy via HTML:
<button [cdkCopyToClipboard]="longText" [cdkCopyToClipboardAttempts]="2">Copy text</button>
Reference: https://material.angular.io/cdk/clipboard/overview
As of Angular Material v9, it now has a clipboard CDK
It can be used as simply as
<button [cdkCopyToClipboard]="This goes to Clipboard">Copy this</button>
I know this has already been highly voted in here by now, but I'd rather go for a custom directive approach and rely on the ClipboardEvent as @jockeisorby suggested, while also making sure the listener is correctly removed (same function needs to be provided for both the add and remove event listeners)
stackblitz demo
import { Directive, Input, Output, EventEmitter, HostListener } from "@angular/core";
@Directive({ selector: '[copy-clipboard]' })
export class CopyClipboardDirective {
@Input("copy-clipboard")
public payload: string;
@Output("copied")
public copied: EventEmitter<string> = new EventEmitter<string>();
@HostListener("click", ["$event"])
public onClick(event: MouseEvent): void {
event.preventDefault();
if (!this.payload)
return;
let listener = (e: ClipboardEvent) => {
let clipboard = e.clipboardData || window["clipboardData"];
clipboard.setData("text", this.payload.toString());
e.preventDefault();
this.copied.emit(this.payload);
};
document.addEventListener("copy", listener, false)
document.execCommand("copy");
document.removeEventListener("copy", listener, false);
}
}
and then use it as such
<a role="button" [copy-clipboard]="'some stuff'" (copied)="notify($event)">
<i class="fa fa-clipboard"></i>
Copy
</a>
public notify(payload: string) {
// Might want to notify the user that something has been pushed to the clipboard
console.info(`'${payload}' has been copied to clipboard`);
}
Note: notice the window["clipboardData"]
is needed for IE as it does not understand e.clipboardData
You can achieve this using Angular modules:
navigator.clipboard.writeText('your text').then().catch(e => console.error(e));
The best way to do this in Angular and keep the code simple is to use this project.
https://www.npmjs.com/package/ngx-clipboard
<fa-icon icon="copy" ngbTooltip="Copy to Clipboard" aria-hidden="true"
ngxClipboard [cbContent]="target value here"
(cbOnSuccess)="copied($event)"></fa-icon>
Source: Stackoverflow.com