I have an Angular 9 app which I need to get a copy to clipboard of url copied when clicked. This is what I have so far:
It copies but not on first attempt only on second attempt is it consoled. Then the clicks stack up so the third click it shows it was clicked 3 times. Why? What am I doing wrong here?
JavaScript
x
36
36
1
<div id="dd" class="dropdown form-group position-relative col-12 col-md-6 save-dialog__form-group">
2
<label for="dropdown" class="col-6 col-md-3 editor-wrapper__label">Select Image:</label>
3
<div class="col-6 col-md-9">
4
<a data-flip="false" data-boundary="dd" href="#" class="dropdown-toggle" data-toggle="dropdown">Images</a>
5
<ul class="dropdown-menu dropdown-menu-down dropdown-menu-right">
6
<li id="{{ 'image-copy-' + i }}" (click)="copyToClipboard($event)" *ngFor="let availableImage of imageOptions; let i = index" class="image-option line-item">
7
<div class="image">
8
<img src="{{ availableImage.relLink }}" />
9
</div>
10
<div class="mark-down example raw-code">
11
{{ availableImage.markDown }}
12
</div>
13
</li>
14
</ul>
15
</div>
16
</div>
17
18
copyToClipboard(event) {
19
var lineItem = document.getElementsByClassName('line-item');
20
var lineItemLength = lineItem.length;
21
for (var i = 0; i < lineItemLength; i++) {
22
lineItem[i].addEventListener('click', function () {
23
console.log(this.id);
24
var el = document.getElementById(this.id);
25
el.setAttribute('contenteditable', 'true');
26
el.focus();
27
document.execCommand('selectAll');
28
document.execCommand('copy');
29
el.setAttribute('contenteditable', 'false');
30
el.blur();
31
32
}, false);
33
34
}
35
}
36
Advertisement
Answer
I was able to resolve this issue by using the code below:
JavaScript
1
11
11
1
copyToClipboard(event) {
2
var target = event.target || event.srcElement || event.currentTarget;
3
4
target.setAttribute('contenteditable', 'true');
5
target.focus();
6
document.execCommand('selectAll');
7
document.execCommand('copy');
8
target.setAttribute('contenteditable', 'false');
9
target.blur();
10
}
11