Search code examples
angularng-bootstrapng2-dragula

create drag and drop sortable list with angular5 and ng-bootstrap


I've got most of my app working and the last part is to show a list of items the user can rearrange in different order and save it in that new order. I've been developing using angular5 (cli) and ng-bootstrap.

How do I create such list? I see it's possible with ngx-bootstrap (https://valor-software.com/ngx-bootstrap/#/sortable) but I would really rather not change now that I'm almost done. Is there a way to accomplish this using ng-bootstrap?

Edit to add example data

The data have this kind of structure (array of objects):

data = [
  {name: 'adam',id: 'asedf'}, 
  {name: 'brian', id: 'aeqww'}, 
  {name: 'carl', id: '34534'}
]

Called from the html like

<ul>
  <li *ngFor="let person of data; let i=index;">{{person.name}}</li>
</ul>

And I want the user to be able to rearrange the list of names and have it reflected in the underlying data model.


Solution

  • What I finally did was to skip ng-bootstrap and use Dragula.

    The HTML template:

    <ul [dragula]='"thebag"' [dragulaModel]="data">
      <li *ngFor="let person of data">person.name</li>
    </ul>
    

    The component:

    import { DragulaService } from 'ng2-dragula';
    
    export class MyComponent implements OnInit {
      data: any[];
    
    constructor(private dragulaService: DragulaService) {
      dragulaService.setOptions('thebag', {});
      dragulaService.dropModel.subscribe((value) => {
        this.onDropModel(value);
      })
      this.data = [];
    }
    private onDropModel(args: any): void {
      const [el, target, source] = args;
      console.log('onDropModel:');
      console.log(el);
      console.log(target);
      console.log(source);
    }
    
    save() {
      console.log(this.data);
      }
    }