我正在尝试实现一个图标,单击该图标会将变量保存到用户的剪贴板中。我目前已经尝试了几个库,但没有一个能够这样做。
如何在Angular 5中将变量正确复制到用户的剪贴板?
答案 0 :(得分:111)
解决方案1:复制任何文字
<强> HTML 强>
<button (click)="copyMessage('This goes to Clipboard')" value="click to copy" >Copy this</button>
.ts文件
copyMessage(val: string){
let 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:从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>
答案 1 :(得分:31)
我知道这已经在这里获得了很高的评价,但是我宁愿使用自定义指令方法,并像@jockeisorby所建议的那样依赖ClipboardEvent,同时还要确保正确删除了侦听器(相同的功能需要同时为添加和删除事件侦听器提供)
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);
}
}
然后按原样使用
<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`);
}
注意:请注意,window["clipboardData"]
对于IE是必需的,因为它不了解e.clipboardData
答案 2 :(得分:29)
我认为这是复制文本时更加简洁的解决方案:
save()
然后在html中的click事件上调用copyToClipboard。 (click)=“ copyToClipboard('texttocopy')”
答案 3 :(得分:23)
从Angular Material v9开始,它现在具有剪贴板CDK
它可以简单地用作
<button [cdkCopyToClipboard]="This goes to Clipboard">Copy this</button>
答案 4 :(得分:8)
您可以使用Angular模块来实现此目的:
navigator.clipboard.writeText('your text').then().catch(e => console.error(e));
答案 5 :(得分:6)
使用角度cdk复制
Module.ts
import {ClipboardModule} from '@angular/cdk/clipboard';
以编程方式复制字符串:MyComponent.ts,
class MyComponent {
constructor(private clipboard: Clipboard) {}
copyHeroName() {
this.clipboard.copy('Alphonso');
}
}
点击要通过HTML复制的元素:
<button [cdkCopyToClipboard]="longText" [cdkCopyToClipboardAttempts]="2">Copy text</button>
答案 6 :(得分:3)
使用navigator.clipboard.writeText
将内容复制到剪贴板
navigator.clipboard.writeText(content).then().catch(e => console.error(e));
答案 7 :(得分:0)
jockeisorby答案的修改版本,该版本修复了未正确删除事件处理程序的情况。
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);
}
答案 8 :(得分:0)
以下方法可用于复制邮件:-
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);
}
答案 9 :(得分:0)
在Angular中做到这一点并保持代码简单的最佳方法是使用此项目。
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>
答案 10 :(得分:0)
第一个建议的解决方案有效,我们只需要更改
selBox.value = val;
收件人
selBox.innerText = val;
即
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.innerText = val;
document.body.appendChild(selBox);
selBox.focus();
selBox.select();
document.execCommand('copy');
document.body.removeChild(selBox);
}
答案 11 :(得分:0)
// for copy the text
import { Clipboard } from "@angular/cdk/clipboard"; // first import this in .ts
constructor(
public clipboard: Clipboard
) { }
<button class="btn btn-success btn-block"(click) = "onCopy('some text')" > Copy< /button>
onCopy(value) {
this.clipboard.copy(value);
}
// for paste the copied text on button click :here is code
<button class="btn btn-success btn-block"(click) = "onpaste()" > Paste < /button>
onpaste() {
navigator['clipboard'].readText().then(clipText => {
console.log(clipText);
});
}