javascript - Angular 10:我正在尝试从跨度复制字符串数据,而不使用 HTML 中的 @Input 括号
问题描述
我正在尝试从跨度、输入、按钮等复制元素,而输入周围没有 [],这样<button copyOnClick>testing the data</button>
应该复制测试数据。当我在copyOnClick <button [copyOnClick]="index + 1"> {{index + 1}}</button>
周围有括号时它确实有效,它复制了1但我想在按钮内获取文本,因此如果我也将它添加到跨度或输入中,它可以更具动态性。
这是我的指令
@Directive({
selector: '[copyOnClick]'
})
export class CopyOnClickDirective {
@Input('copyOnClick')
public url: any;
@Output('copied')
public copied: EventEmitter<string> = new EventEmitter<string>();
@HostListener('click', ['$event'])
public onClick(event: MouseEvent): void {
event.preventDefault();
if (!this.url) return;
let listener = (e: ClipboardEvent) => {
let clipboard = e.clipboardData || window['clipboardData'];
clipboard.setData('text', this.url.toString());
e.preventDefault();
this.copied.emit(this.url);
};
document.addEventListener('copy', listener, false);
document.execCommand('copy');
document.removeEventListener('copy', listener, false);
console.log(this.url);
}
}
这是 HTML 代码。
<button class="btn-numbers btn font-weight-medium btn-light" [copyOnClick]="index + 1">{{ index + 1 }}</button>
解决方案
您要做的是将宿主元素 ref 注入指令构造函数 ( private readonly _elementRef: ElementRef
) 并使用它来获取实际内容。
然后您可以使用this._elementRef.nativeElement
访问内部 html(用于跨度)或值(用于文本输入)。
推荐阅读
- reactjs - 无法解析“反应路由器”
- server - 在服务器模式下启动 GSM 调制解调器时如何获取公共 IP 地址?
- excel - 跨多个工作表求和时忽略隐藏工作表
- .htaccess - 如何在不影响根目录索引页的情况下从 url 隐藏子目录
- javascript - JavaScript通过innerText罢工不起作用
- swift - 创建一个“新建”按钮,在 Swift 中创建 3 个 UI 文本字段
- javascript - function.promise.then() 和 function.then() 的区别
- android - 我无法使用 oauth 2.0 与我的服务器使用 android 连接
- typescript - 打字稿中的“鸭子”打字与函数参数
- go - 为什么复制指向 Go 结构的指针不会保持与原始结构的链接?