Clipboard API and Angular

broggi

Broggi Quentin

Posted on February 2, 2024

Clipboard API and Angular

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>
Enter fullscreen mode Exit fullscreen mode

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);

        }

      }

    }

  }
Enter fullscreen mode Exit fullscreen mode

Remember to declare your imageSrc as public:

  public imageSrc = "";
Enter fullscreen mode Exit fullscreen mode

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));

  }
Enter fullscreen mode Exit fullscreen mode

This way, no matter where the focus is, you can retrieve the file.

πŸ’– πŸ’ͺ πŸ™… 🚩
broggi
Broggi Quentin

Posted on February 2, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related