在Angular2 Typescript框架中,有没有办法复制剪贴板(多浏览器)中的文本?
我只找到使用Javascript的源码,例如
document.execCommand('copy')发布于 2016-03-31 18:16:02
您可以在clipboard.js库周围实现一个Angular2指令。
首先将库配置到SystemJS中:
<script>
System.config({
map: {
clipboard: 'https://cdn.rawgit.com/zenorocha/clipboard.js/master/dist/clipboard.js'
},
packages: {
'app': {
defaultExtension: 'js'
}
}
});
(...)
</script>我们希望能够通过指令将剪贴板附加到元素上,并提供我们想要链接的DOM元素作为参数。指定到指定目标元素的值将用于复制其文本。下面是一个使用示例:
<div>
<input #foo/>
<button [clipboard]="foo">Copy</button>
</div>该指令的实现如下:
import {Directive,ElementRef,Input,Output,EventEmitter} from 'angular2/core';
import Clipboard from 'clipboard';
@Directive({
selector: '[clipboard]'
})
export class ClipboardDirective {
clipboard: Clipboard;
@Input('clipboard')
elt:ElementRef;
@Output()
clipboardSuccess:EventEmitter<any> = new EventEmitter();
@Output()
clipboardError:EventEmitter<any> = new EventEmitter();
constructor(private eltRef:ElementRef) {
}
ngOnInit() {
this.clipboard = new Clipboard(this.eltRef.nativeElement, {
target: () => {
return this.elt;
}
});
this.clipboard.on('success', (e) => {
this.clipboardSuccess.emit();
});
this.clipboard.on('error', (e) => {
this.clipboardError.emit();
});
}
ngOnDestroy() {
if (this.clipboard) {
this.clipboard.destroy();
}
}
}有关示例,请参阅此柱塞:https://plnkr.co/edit/elyMcP5PX3UP4RkRQUG8?p=preview。
发布于 2017-04-04 16:42:13
我只从https://github.com/pehu71/copy-component/blob/master/src/simple/copy.component.ts works得到了一个方法,即使在Android4.1.2上也是如此
copy(val) {
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);
}发布于 2016-06-10 01:07:14
致敬@ThierryTemplier,
根据他的回答,我在github & npm上做了一个指令和分享。
这是github上的项目
更新日期: 4/30/2017
这个库不再依赖于clipboard.js了。
就是Angular!
快速示例(组件代码):
import { ClipboardService } from 'ngx-clipboard'
...
constructor(private _clipboardService: ClipboardService){
...
}
// not sure, but this should the result of user interaction (e.g. (click) )
copyToClipboard(){
const text = computeText();
this._clipboardService.copyFromContent(text)
}https://stackoverflow.com/questions/36328159
复制相似问题