Implementing Native Drag-and-Drop in Angular

deekshithrajbasa

Deekshith Raj Basa 🔥

Posted on March 5, 2024

Implementing Native Drag-and-Drop in Angular

Drag-and-drop functionality can significantly enhance the user experience in your Angular applications, allowing for intuitive interactions like reordering items, building lists, and managing file uploads.

Leverage the browser's built-in Drag-and-Drop API for a straightforward implementation. Utilize the dragstart, dragover, and drop events to capture drag interactions and update your application state accordingly.

HTML

<div class="draggable" (dragover)="onDragOver($event)" (drop)="onDrop($event)"> Drag and Drop
    </div>
<ng-container *ngIf="droppedImage">
  <img  [src]="droppedImage" alt="Dropped Image"/>
</ng-container>
Enter fullscreen mode Exit fullscreen mode

Typescript

droppedImage: string | null = null;

  onDragOver(event: DragEvent) {
    event.preventDefault(); // Allow dropping
  }

  onDrop(event: DragEvent) {
    if (event.dataTransfer) {
      const files = event.dataTransfer.files;
      if (files && files.length === 1 && files[0].type.startsWith('image/')) {
        const reader = new FileReader();
        reader.readAsDataURL(files[0]);
        reader.onload = (e) => {
          this.droppedImage = e?.target?.result as string;
        };
      } else {
        alert('Please drop an image file only.');
      }
    }
    event.preventDefault(); // Not letting the browser to open image in new tab
  }

Enter fullscreen mode Exit fullscreen mode

Native Drag-and-Drop in Angular

Here's the full working demo: https://stackblitz.com/edit/native-drag-drop-angular-deekshith-raj-basa?file=src%2Fmain.ts

💖 💪 🙅 🚩
deekshithrajbasa
Deekshith Raj Basa 🔥

Posted on March 5, 2024

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

Sign up to receive the latest update from our blog.

Related