Angular 5-复制到剪贴板 [英] Angular 5 - Copy to clipboard
本文介绍了Angular 5-复制到剪贴板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试实现一个图标,单击该图标会将变量保存到用户的剪贴板.我目前已经尝试了几个库,但没有一个库能够这样做.
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.
如何在Angular 5中将变量正确复制到用户剪贴板?
How do I properly copy a variable to the user's clipboard in Angular 5?
推荐答案
解决方案1:复制任何文本
HTML
<button (click)="copyMessage('This goes to Clipboard')" value="click to copy" >Copy this</button>
.ts文件
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.value = val;
document.body.appendChild(selBox);
selBox.focus();
selBox.select();
document.execCommand('copy');
document.body.removeChild(selBox);
}
解决方案2:从文本框复制
Solution 2: Copy from a TextBox
HTML
<input type="text" value="User input Text to copy" #userinput>
<button (click)="copyInputMessage(userinput)" value="click to copy" >Copy from Textbox</button>
.ts文件
/* To copy Text from Textbox */
copyInputMessage(inputElement){
inputElement.select();
document.execCommand('copy');
inputElement.setSelectionRange(0, 0);
}
解决方案3:导入第三方指令 ngx-clipboard
<button class="btn btn-default" type="button" ngxClipboard [cbContent]="Text to be copied">copy</button>
解决方案4:自定义指令
如果您喜欢使用自定义指令,请查看Dan Dohotaru的 answer ,这是使用ClipboardEvent
实现的一种优雅的解决方案.
If you prefer using a custom directive, Check Dan Dohotaru's answer which is an elegant solution implemented using ClipboardEvent
.
这篇关于Angular 5-复制到剪贴板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文