html
<a [appCopy]="td?.orderNo">复制</a>
ts
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import Clipboard from "clipboard";
@Directive({
selector: '[appCopy]'
})
export class CopyDirective {
@Input("appCopy") value;
/** 监听元素的click事件 */
@HostListener('click') onClick() {
this.copy()
}
constructor(
private msg: NzMessageService,
private ele: ElementRef
) {}
copy(){
const clipboard = new Clipboard(this.ele.nativeElement, {
text: () => {
return this.value
}
});
clipboard.on('success', e => {
this.msg.success("复制成功")
// 释放内存, 一定要清除事件,不然msg会弹出很多次
clipboard.off('error')
clipboard.off('success')
clipboard.destroy()
})
clipboard.on('error', e => {
// 不支持复制
this.msg.warning("该浏览器不支持自动复制")
// 释放内存,一定要清除事件,不然msg会弹出很多次
clipboard.off('error')
clipboard.off('success')
clipboard.destroy()
})
// 通过调试源码发现,传入的this.ele.nativeElement缺少currentTarget属性,在这里手动加上currentTarget属性
const target = this.ele.nativeElement;
target.currentTarget = this.ele.nativeElement;
// 默认需要调用一次,不然第一次点击无效
clipboard.onClick(target);
}
}
网友评论