Clipboard API and Angular
Broggi Quentin
Posted on February 2, 2024
In this article, I will show you how to display an image copied directly into your application using Ctrl+V.
Configuration in the Template
In your template, you will create a div that listens to the (paste) event. This event will be triggered when the user performs a CTRL+V, and it defines an area in your application where users can paste content:
<div style="height: 500px; width: 500px;" (paste)="onPaste($event)" >
<img *ngIf="imageSrc" [src]="imageSrc" alt="Pasted Image">
</div>
Processing Clipboard Data
This will provide you with a ClipboardEvent, in which you can find everything that has been copied, be it text, an image, a PDF file, etc. Here, I will filter based on the MIME type of the file to ensure it is indeed an image. However, you can also paste other file types like a Word or PDF file directly into an , for example, using Ctrl+V.
public onPaste(event: ClipboardEvent): void {
const clipboardData = event.clipboardData;
if (clipboardData) {
const items = clipboardData.items;
// Check if there is at least one item and if the first item is an image
if (items.length > 0 && items[0].type.indexOf('image') !== -1) {
// Attempt to retrieve the image file from the clipboard item
const blob = items[0].getAsFile();
if (blob) {
const reader = new FileReader();
reader.onload = (event: ProgressEvent<FileReader>) => {
if (event.target)
// Setting the component's imageSrc property to the base64 data URL of the image
this.imageSrc = event.target.result as string;
};
reader.readAsDataURL(blob);
}
}
}
}
Remember to declare your imageSrc as public:
public imageSrc = "";
Global Listening on the Document
You also have the option to set up global listening on the entire document, not just on a div, in this manner:
constructor(@Inject(DOCUMENT) private document: Document) { }
ngOnInit() {
this.document.addEventListener('paste', this.onPaste.bind(this));
}
This way, no matter where the focus is, you can retrieve the file.
Posted on February 2, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.