ngx-drag-drop

repository·master·Indexed 43 days ago

https://github.com/christoffritz/ngx-drag-drop

An Angular library providing declarative drag-and-drop functionality using the HTML5 Drag-And-Drop API. It supports sortable lists, nesting, custom drag images, and dropzones that can accept external native content. Features include the [dndDraggable] and [dndDropzone] directives, custom drag handles, and experimental touch support via the @dragdroptouch/drag-drop-touch polyfill.

Tokens
6.1K
Snippets
26
Records
29
Agent score
54%

What's inside ngx-drag-drop

  1. Configure ngx-drag-drop in your Angular Module

    master

    To use the library, import DndModule into your Angular module (e.g., AppModule).

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    
    import { DndModule } from 'ngx-drag-drop';
    
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        DndModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule {
    }
  2. Enable Touch Support (Experimental)

    master

    The library uses the native HTML5 Drag and Drop API, which is not supported by most mobile browsers (like iOS Safari). To enable basic touch support, you must use the @dragdroptouch/drag-drop-touch polyfill.

    import { enableDragDropTouch } from "@dragdroptouch/drag-drop-touch";
    
    enableDragDropTouch();
  3. Import DndModule to use ngx-drag-drop

    master

    To use the drag and drop functionality in your Angular application, import the DndModule into your component's NgModule or standalone component imports. This module exports the core directives required to implement draggable elements, dropzones, handles, and placeholders.

    import { DndModule } from 'ngx-drag-drop';
    
    @NgModule({
      imports: [
        DndModule
      ],
      // ...
    })
    export class MyModule {}
  4. Implement Dropzones with [dndDropzone]

    master

    Use the [dndDropzone] directive to create a target for draggable elements.

    Key features:

    • [dndDropzone]: An array of allowed types to restrict what can be dropped.
    • [dndEffectAllowed]: Restricts the allowed drop effects.
    • [dndDisableIf]: Conditionally disables the dropzone.
    • [dndAllowExternal]: If true, allows dropping content that is not a [dndDraggable] (e.g., native files, images, or text).
    • [dndHorizontal]: If true, influences how the placeholder position is calculated for horizontal lists.
    • dndPlaceholderRef: A directive used on a child element to define the placeholder that appears during dragging.

    Events:

    • (dndDragover): Emits when a draggable is dragged over the dropzone.
    • (dndDrop): Emits when a successful drop occurs, providing a DndDropEvent object.
    <section dndDropzone
             (dndDragover)="onDragover($event)"
             (dndDrop)="onDrop($event)">
    
        dropzone
    
        <div style="border: 1px orangered solid; border-radius: 5px; padding: 15px;" dndPlaceholderRef>
            placeholder
        </div>
    
    </section>
  5. Implement Draggable elements with [dndDraggable]

    master

    Use the [dndDraggable] directive to make an element draggable.

    Key features:

    • [dndDraggable]: The data attached to the drag (note: data is handled via JSON.stringify/JSON.parse, so use simple objects/POJOs).
    • [dndEffectAllowed]: Restricts the allowed drop effects.
    • [dndDisableIf]: Conditionally disables dragging.
    • [dndHideDraggingSource]: If true, the original element is hidden from the layout while dragging, which is useful for sortable lists or grids.
    • dndHandle: A directive used inside a draggable element to restrict the drag start to a specific child element.
    • dndDragImageRef: A directive used on a child element to designate it as the custom drag image.

    Events:

    • (dndStart): Emits on drag start.
    • (dndEnd): Emits on drag end.
    • (dndMoved): Emits when dropped with effect "move".
    • (dndCopied): Emits when dropped with effect "copy".
    • (dndLinked): Emits when dropped with effect "link".
    • (dndCanceled): Emits when the drag is canceled.
    <div [dndDraggable]="draggable.data"
         [dndEffectAllowed]="draggable.effectAllowed"
         [dndDisableIf]="draggable.disable"
         [dndHideDraggingSource]="true"
         (dndStart)="onDragStart($event)"
         (dndCopied)="onDraggableCopied($event)"
         (dndLinked)="onDraggableLinked($event)"
         (dndMoved)="onDraggableMoved($event)"
         (dndCanceled)="onDragCanceled($event)"
         (dndEnd)="onDragEnd($event)">
    
        <div *ngIf="draggable.handle" dndHandle>HANDLE</div>
    
        draggable ({{draggable.effectAllowed}}) <span [hidden]="!draggable.disable">DISABLED</span>
    
        <div dndDragImageRef>DRAG_IMAGE</div>
    </div>
  6. Configure DndDropzoneDirective inputs

    master

    The DndDropzoneDirective accepts several configuration inputs to control its behavior:

    • [dndDropzone]: An array of strings (e.g., ['type1', 'type2']) or an empty string ''. Only items with a matching type can be dropped here. If not provided, all types are allowed.
    • [dndEffectAllowed]: The allowed DropEffect (e.g., 'move', 'copy').
    • [dndAllowExternal]: Boolean. If true, allows items dragged from outside the application to be dropped.
    • [dndHorizontal]: Boolean. If true, the placeholder will be positioned to the left or right of elements instead of above/below.
    • [dndDragoverClass]: String. The CSS class applied to the dropzone when an item is being dragged over it (default: 'dndDragover').
    • [dndDropzoneDisabledClass]: String. The CSS class applied when the dropzone is disabled (default: 'dndDropzoneDisabled').
    • [dndDisableIf]: Boolean. Disables the dropzone entirely.
    • [dndDisableDropIf]: Boolean. Disables dropping specifically, while potentially still allowing dragover events.
  7. Angular Version Compatibility

    master

    Starting with v13, the library major version matches the Angular major version. For older Angular versions (v4–v12), use ngx-drag-drop v2.x.

    | Angular | ngx-drag-drop |
    | ------- | ------------- |
    | 22.x    | 22.x          |
    | 21.x    | 21.x          |
    | 20.x    | 20.x          |
    | 19.x    | 19.x          |
    | 18.x    | 18.x          |
    | 17.x    | 17.x          |
    | 16.x    | 16.x          |
    | 15.x    | 15.x          |
    | 14.x    | 14.x          |
    | 13.x    | 13.x          |
  8. Enable touch support with enableDragDropTouch()

    master

    To enable experimental touch support for drag and drop operations, use the enableDragDropTouch function from the @dragdroptouch/drag-drop-touch module. This function initializes touch event listeners to simulate drag and drop behavior on touch-enabled devices.

    Parameters

    • dragRoot (optional): The root element that acts as a drag source. If not provided, it defaults to the document.
    • dropRoot (optional): The root element that acts as a drop target. If not provided, it defaults to the document.
    • options (optional): A record of configuration options to customize the touch behavior.
    import { enableDragDropTouch } from '@dragdroptouch/drag-drop-touch';
    
    // Basic usage on the entire document
    enableDragDropTouch();
    
    // Targeted usage on specific elements
    enableDragDropTouch(document.getElementById('drag-container')!, document.getElementById('drop-container')!, { /* options */ });
  9. Manage drag and drop data with setDragData and getDropData

    master

    The library provides utilities to serialize and deserialize drag-and-drop data using a custom MIME type (application/x-dnd). This ensures that data passed during a drag operation is structured and identifiable.

    Data Structure

    Data is handled via the DragDropData interface:

    • data: The actual payload (any type).
    • type: An optional string used to create specific sub-MIME types (e.g., application/x-dnd-mytype).

    Usage

    • Use setDragData(event, data, effectAllowed) to attach data to a DragEvent during the dragstart phase.
    • Use getDropData(event, dragIsExternal) to retrieve the data during the drop phase. If dragIsExternal is true, the function only returns data if it matches the custom MIME type format.
    import { setDragData, getDropData, DragDropData } from './dnd-utils';
    
    // During dragstart
    const myData: DragDropData = { data: { id: 123 }, type: 'user-item' };
    setDragData(event, myData, 'move');
    
    // During drop
    const droppedData = getDropData(event, false);
    console.log(droppedData.data); // { id: 123 }