@Input()copyText:string;
constructor(
private renderer: Renderer2,
private el: ElementRef
) { }
@HostListener('click', ['$event'])
public onClick () {
if (!this.copyText) {
return;
}
const dom =this.renderer.createElement('div');
const el =this.el.nativeElement;
const range =document.createRange();
this.renderer.setAttribute(dom,'id','copyId');
this.renderer.setProperty(dom,'innerHTML',this.copyText);
el.appendChild(dom);
range.selectNode(el.querySelector('#copyId'));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
const success =document.execCommand('copy');
if (success) {
console.log('复制成功');
el.removeChild(dom);
}else {
console.log('该浏览器不支持!');
}
}
使用方法: <span [copyText]="'复制内容"></span>