Report this

What is the reason for this report?

Drag & Drop in Your Angular Apps With ng2-dragula

Published on May 25, 2017
Drag & Drop in Your Angular Apps With ng2-dragula

Dragula is a popular JavaScript library for drag & drop, and ng2-dragula is a wrapper to use Dragula in Angular 2+ apps. Let’s see how it’s used.

Installation

First add ng2-dragula to your project using Yarn or npm:

# Yarn
$ yarn add ng2-dragula

# npm
$ npm install ng2-dragula --save

Now import DragulaModule and add it to your NgModule’s imports:

app.module.ts
// ...

import { DragulaModule } from 'ng2-dragula/ng2-dragula';

And the last setup step is to add the Dragula CSS file to the project. If you’re using the Angular CLI, you can simply add the CSS file path in your .angular-cli.json file:

"styles": [
  "styles.css",
  "../node_modules/dragula/dist/dragula.css"
],

Using ng2-dragula

Now to use it, it’s as simple as using the dragula directive on a container element in your template and providing a group name. Groups in Dragula are called bags:

<ul [dragula]='"bag-items"'>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>

And if you have multiple distinct containers:

<ul [dragula]='"bag-items"'>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>

<ul [dragula]='"bag-people"'>
  <li *ngFor="let person of people">{{ person }}</li>
</ul>

If you want the changes in order to be synced in your items array, simply use the dragulaModel directive with the name of the model. This way, when items are re-ordered via drag & drop, the items array will also have its items re-ordered to reflect the changes:

<ul [dragula]='"bag-items"' [dragulaModel]='items'>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>

Events and Configuration Options

You can use the DragulaService to hook into events or to set configuration options.

Configuration

To use the service, first import it and inject it in the constructor. Then it’s as simple as calling the setOptions method, specifying the container and providing an object literal with your desired options:

import { Component, OnInit } from '@angular/core';

import { DragulaService } from 'ng2-dragula/ng2-dragula';

@Component({ ... })
export class AppComponent implements OnInit {
  constructor(private dragula: DragulaService) {
    this.dragula.setOptions('bag-items', {
      revertOnSpill: true
    });
  }
}

You can set options such as direction, copy, copySortSource, revertOnSpill, removeOnSpill and mirrorContainer. Refer to the project page for configuration options.

Events

You can hook into the drag, drop, over and out events and each of the events return an observable. Here’s a complete example where a message is displayed when dragging or dropping an item:

import { Component, OnInit } from '@angular/core';

import { DragulaService } from 'ng2-dragula/ng2-dragula';

@Component({ ... })
export class AppComponent implements OnInit {
  msg = '';

  items = [
    'Candlestick',
    'Dagger',
    'Revolver',
    'Rope',
    'Pipe',
    'Wrench'
  ];

  constructor(private dragula: DragulaService) { }

  ngOnInit() {
    this.dragula
      .drag
      .subscribe(value => {
        this.msg = `Dragging the ${ value[1].innerText }!`;
      });

    this.dragula
      .drop
      .subscribe(value => {
        this.msg = `Dropped the ${ value[1].innerText }!`;

        setTimeout(() => {
          this.msg = '';
        }, 1000);
      });
  }
}

The value returned by both the drag and the drop event observables is an array containing the bag name (e.g.: bag-items), the dragged element and the container element (the <ul> element).

Our App at Work! 🎥

Example of using ng2-dragula

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author

Alligator
Alligator
Author
See author profile

Alligator.io is a developer-focused resource that offers tutorials and insights on a wide range of modern front-end technologies, including Angular 2+, Vue.js, React, TypeScript, Ionic, and JavaScript.

Category:
Tags:
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Was this helpful?


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.