Copy text to Clipboard from multiple UI elements
Handle case of <span/> inner text
Generic method to handle all elements
1. Component - HTML
<div fxLayout="row" fxLayoutAlign="space-between center" style="padding: 50px;">
<div><span>NAME: </span> <span id="nameEl{{name}}">{{name}}</span></div>
<div (click)="copyToClipboard('nameEl'+name)"><mat-icon fontSet="material-icons-outlined">bookmarks</mat-icon></div>
</div>
<div fxLayout="row" fxLayoutAlign="space-between center" style="padding: 50px;">
<div><span>SURNAME: </span> <span id="surnameEl{{surname}}">{{surname}}</span></div>
<div (click)="copyToClipboard('surnameEl'+surname)"><mat-icon fontSet="material-icons-outlined">bookmarks</mat-icon></div>
</div>
2. Component - TS
import { Component, OnInit } from "@angular/core";
@Component({ selector: "jhi-test-comp", templateUrl: "./test-comp.component.html", styleUrls: ["./test-comp.component.scss"] })
export class TestCompComponent implements OnInit {
name = "Myname";
surname = "MySurname";
constructor() {}
ngOnInit(): void {}
// Handles case of span element
// Copy span text to temporary input
// Execute command to copy to clipboard
copyToClipboard(id: string): void {
const copyEl = document.getElementById(id);
const inputHelper = document.createElement('input');
if (inputHelper !== null && copyEl !== null && copyEl.textContent !== null) {
// Remove white spaces
inputHelper.value = copyEl.textContent.replace(/\s/g, '');
document.body.appendChild(inputHelper);
inputHelper.select();
document.execCommand('Copy');
inputHelper.remove();
}
}
Δεν υπάρχουν σχόλια:
Δημοσίευση σχολίου
What may be missing, or could get better?