I am working on an Angular 9 application where I want to implement the functionality of copying the URL to clipboard when clicked. Currently, I have the following code:
The issue I am facing is that it only copies the URL on the second attempt and then starts stacking up the clicks, so on the third click it shows that it was clicked three times. Can someone help me understand why this is happening? What am I missing in my implementation?
<div id="dd" class="dropdown form-group position-relative col-12 col-md-6 save-dialog__form-group">
<label for="dropdown" class="col-6 col-md-3 editor-wrapper__label">Select Image:</label>
<div class="col-6 col-md-9">
<a data-flip="false" data-boundary="dd" href="#" class="dropdown-toggle" data-toggle="dropdown">Images</a>
<ul class="dropdown-menu dropdown-menu-down dropdown-menu-right">
<li id="{{ 'image-copy-' + i }}" (click)="copyToClipboard($event)" *ngFor="let availableImage of imageOptions; let i = index" class="image-option line-item">
<div class="image">
<img src="{{ availableImage.relLink }}" />
</div>
<div class="mark-down example raw-code">
{{ availableImage.markDown }}
</div>
</li>
</ul>
</div>
</div>
copyToClipboard(event) {
var lineItem = document.getElementsByClassName('line-item');
var lineItemLength = lineItem.length;
for (var i = 0; i < lineItemLength; i++) {
lineItem[i].addEventListener('click', function () {
console.log(this.id);
var el = document.getElementById(this.id);
el.setAttribute('contenteditable', 'true');
el.focus();
document.execCommand('selectAll');
document.execCommand('copy');
el.setAttribute('contenteditable', 'false');
el.blur();
}, false);
}
}