Add drag and drop on ionic 2 by plugin dragula

ionic 2 didn’t provide drag and drop, so we going to add it by our own.

i am using ionic 2 + angular 2 + typescript

first we need to download dragula, open Terminal

cd project
npm install ng2-dragula dragula --save

it may show something on terminal said few of thing was not install, but don’t need to worry about it.

go to directory ../project/node_modules/ you now can see two new folder name dragula and ng2-dragula, that’s mean you now can use dragula in you project.

go to project/src/app/app.module.ts

add this on top of page

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

on

@NgModule({
  imports: [
    IonicModule.forRoot(MyApp),
    DragulaModule    //

now we going to our page that we want to add drag and drop, for my project page call home

so open home.ts, on top of this page add

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

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
  , providers: [DragulaService]  //

on constructor add

constructor(private dragulaService: DragulaService){
dragulaService.setOptions('item-list', {
          revertOnSpill: true
        });
dragulaService.dropModel.subscribe((value) => {   
        this.onDropModel(value.slice(1));
      });
      dragulaService.removeModel.subscribe((value) => {
        this.onRemoveModel(value.slice(1));
      });

}

  private onDropModel(args) {
    let [el, target, source] = args;
    // do something else
  }

  private onRemoveModel(args) {
    let [el, source] = args;
    // do something else
  }


http://valor-software.com/ng2-dragula/index.html here is demo for dragula,

on home.html, for my personal suggestion, i don’t user ion-list, i am using div.

  
<div class="item_table" *ngFor="let items of cart_items; let spNumber = index">

<div style="min-height:50px; border:1px solid #eee;" [dragula]='"item-list"' [dragulaModel]='items' class='container'>

<div *ngFor="let item of items; let i = index">

          {{item.name}}
         </div>

    </div>

</div>



make sure [dragula] this name “item-list” must match to dragulaService.setOptions on home.ts, you can call it whatever you want, but must be match.

i am pull out the code from my project, so let me know if there any problem or question. i already test it and it work ok on my end 🙂

dragula with ionic 2 tutorial Part 2 – dynamic conditional

Leave a Reply

Your email address will not be published. Required fields are marked *