I have a clickable icon on the page. On click on this icon, I would like to construct some text and copy that in the clipboard
<td><img src='./assets/Copy.gif' (click)="copyToClipboard()" /></td>
and in the Component
copyToClipboard() {
this.textToCopy = this.text1 + this.text2 + this.text3;
this.toastr.info('Copied to Clipboard');
}
I have looked at https://www.npmjs.com/package/ngx-clipboard. However, this package requires to refer to an input element and copy the text from that input element. In my use case, the text needs to be dynamically created and then added to clipboard.
Can I use ngx-clipboard to copy to clipboard or is there be another package that would enable me to achieve this?
Click an element to copyThe cdkCopyToClipboard directive can be used to easily add copy-on-click functionality to an existing element. The directive selector doubles as an @Input() for the text to be copied.
Open the file that you want to copy items from. Select the first item that you want to copy, and press CTRL+C. Continue copying items from the same or other files until you have collected all of the items that you want. The Office Clipboard can hold up to 24 items.
User interaction is mandatory for executing document.execCommand
, which is used for copying text to the clipboard.
See my other answer.
If you don't want to use any third party library, you could use below snippet for copying text to the clipboard.
function copyTextToClipboard(text) {
var txtArea = document.createElement("textarea");
txtArea.id = 'txt';
txtArea.style.position = 'fixed';
txtArea.style.top = '0';
txtArea.style.left = '0';
txtArea.style.opacity = '0';
txtArea.value = text;
document.body.appendChild(txtArea);
txtArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
if (successful) {
return true;
}
} catch (err) {
console.log('Oops, unable to copy');
} finally {
document.body.removeChild(txtArea);
}
return false;
}
Change copyToClipboard
function as below to call the copyTextToClipboard function
copyToClipboard() {
this.textToCopy = this.text1 + this.text2 + this.text3;
var result = this.copyTextToClipboard(this.textToCopy);
if (result) {
this.toastr.info('Copied to Clipboard');
}
}
You need to use ngxClipboard
directive with your image. This is how you need to use it to solve your issue:
<td>
<img src='./assets/Copy.gif' (click)="copyToClipboard()" ngxClipboard [cbContent]="textToCopy" />
</td>
Remember to add ClipboardModule
in your app module. Example code below:
import { ClipboardModule } from 'ngx-clipboard';
@NgModule({
imports: [
// Other Imports
ClipboardModule
],
// Other code
})
export class AppModule { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With