Tutorial

Drag & Drop in Your Angular Apps With ng2-dragula

Published on May 25, 2017
author

Alligator.io

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 authors
Default avatar
Alligator.io

author

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?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


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!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

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.