Angular 2 Dragula Model updating incorrectly

Dan Feinstein picture Dan Feinstein · Dec 7, 2016 · Viewed 15.4k times · Source

Working with ng2-dragula. I'm looking to update the orderNumber for every item in a database using the new dropped order.

dragulaService.dropModel.subscribe((value) => {
  var drake = dragulaService.find('bag-orders').drake
  var models = drake.models
  console.log(models)
})

The new model order that it returns does not reflect the order within the bag.

TL;DR: has anyone implemented reordering within a database onDrop with ng2-dragula?

Answer

darksider picture darksider · Dec 11, 2016

If you want to be able to drag items (without them disappearing) AND fire the dropModel event:

  • Put the [dragula] and [dragulaModel] directives in the parent element. (For example, contrary to the current doc where it says to put them in the <li>, you have to put them in the <ul>

  • Inject the dragularService, and, in the constructor of your component:

  • Call the dragulaService.setOptions for the bag (you can pass an empty dictionary). If you don't call it, dropModelcallback is not fired

  • Subscribe to dropModel

The result:

<!--thecomponent.html-->
<h2>Playlists</h2>
<ul [dragula]='"first-bag"' [dragulaModel]='playlists'>
  <li *ngFor="let playlist of playlists">

//Inside the component.ts  
playlists: Playlist[];

constructor(private youtubeService: YoutubeService, private dragulaService: DragulaService) {

    dragulaService.setOptions('first-bag', {})
    dragulaService.dropModel.subscribe((value) => {
      this.onDropModel(value);
    });
}

private onDropModel(args) {
    //Here, this.playlists contains the elements reordered
}