解决方案一:复制任何文本
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.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 file
/* To copy Text from Textbox */
copyInputMessage(inputElement){
inputElement.select();
document.execCommand('copy');
inputElement.setSelectionRange(0, 0);
}
演示在这里 https://stackblitz.com/edit/angular-6-copy-to-clipboard
解决方案3:导入第 3 方指令ngx剪贴板 https://github.com/maxisam/ngx-clipboard
<button class="btn btn-default" type="button" ngxClipboard [cbContent]="Text to be copied">copy</button>
解决方案4:定制指令
如果您更喜欢使用自定义指令,请查看 Dan Dohotaru 的answer https://stackoverflow.com/a/52949299/443244这是一个优雅的解决方案,使用ClipboardEvent
.
解决方案5:角材料
Angular Material 9+ 用户可以利用内置剪贴板 https://material.angular.io/cdk/clipboard/overview复制文本的功能。还有一些可用的自定义功能,例如限制复制数据的尝试次数。