ionic 7 copy in clipboard without plugin

We can implement copy in clipboard easily in ionic native code using the capacitor plugin. But native plugins are not supported in ionic progressive web applications.


So to achieve this in the Ionic 7 web application we have to apply the code below:

you have to put the value you want to copy in the clipboard in a hidden field in the HTML:


<input type="text" style="display:none" value="Test value" id="inputToBeCopied" />


<ion-button slot="end" color="light" (click)="shareApp()">
Copy in Clipboard
<ion-icon slot="end" name="share-social"></ion-icon>
</ion-button>

Keep in mind input field type should be text not hidden. You have to hide it using the CSS display property.


Now in ts code:


import { DOCUMENT } from '@angular/common';

constructor(@Inject(DOCUMENT) private dom: Document) {
}

async shareApp() {
this.copyElementText('inputToBeCopied');
const toast = await this.toastController.create({
message: 'App URL copied!',
duration: 1500,
position: 'middle',
});
await toast.present();
}


copyElementText(id: string) {
let element: any = null;
try {
element = this.dom.getElementById(id);
element.style.display = 'block';
element.select();
this.dom.execCommand('copy');
}
finally {
if (this.dom == null) {
return;
} else {
this.dom.getSelection()!.removeAllRanges();
element.selectionStart = element.selectionEnd;
}
element.style.display = 'none';
}
}


That's it.

If you want a complete working code you can ping me on my WhatsApp: +919887529835

or download the source code from my website http://bospp.com





No comments:

Post a Comment