DEV Community

Cover image for Implementing Native Drag-and-Drop in Angular
Deekshith Raj Basa 🔥
Deekshith Raj Basa 🔥

Posted on

3 1

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

Top comments (2)

Collapse
 
danishhafeez profile image
Danish Hafeez •

well informative content. i hope all newbies will get help from it.

Best Regard
Danish Hafeez | QA Assistant
ICTInnovations

Collapse
 
deekshithrajbasa profile image
Deekshith Raj Basa 🔥 •

Thanks for the comment, yes this is helpful for all new learners who are learning to build features using the native approach.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up