DEV Community

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

Posted on

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.


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


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.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:

Top comments (2)

danishhafeez profile image
Danish Hafeez

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

Best Regard
Danish Hafeez | QA Assistant

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.