Angular 5 - 复制到剪贴板 [英] Angular 5 - Copy to clipboard
问题描述
我正在尝试实现一个图标,单击该图标时会将变量保存到用户的剪贴板.我目前尝试了几个图书馆,但没有一个能够这样做.
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:从文本框复制
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: 导入第 3 方指令 ngx-clipboard
Solution 3: Import a 3rd party directive 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
.
解决方案 5: Angular Material
Solution 5: Angular Material
Angular material 9 + 用户可以利用内置剪贴板功能来复制文本.还有一些可用的自定义设置,例如限制复制数据的尝试次数.
Angular material 9 + users can utilize the built-in clipboard feature to copy text. There are a few more customization available such as limiting the number of attempts to copy data.
这篇关于Angular 5 - 复制到剪贴板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!