Copy with ng2-dragula

823 views Asked by At

I would like to have my source model to remain unchanged after dragging one element away. Here is what i have sofar: component.ts:

constructor(private dragulaService: DragulaService) {
    this.dragulaService.dropModel('DragItems').subscribe(dropItem => {
        this.text += dropItem.item.data;
    });
}

component.html:

<ul [dragula]="'DragItems'" [dragulaModel]="datas">
    <li *ngFor="let data of datas">
        <div class="list-item-class">
            {{data.value}}
        </div>
    </li>
</ul>

In my target field i already have some text and get the value of the dragged item appended to the end of the existing text, but the dragged item disappears. Thank you for your help!

2

There are 2 answers

0
Quentin Hayot On

You can use options to tell Dragula that your item should be copied and not moved:

copyItem: <T>(item: T) => T

When you have:

  • [(dragulaModel)]
  • copy is true or a function that returns true

... ng2-dragula will have to create a clone of the JS object you picked up. In previous versions of ng2-dragula, there was a terribly buggy, one-size-fits-all clone function. From v2 onwards, you MUST provide your own copyItem function.

If you have a simple object with no nested values, it could be as simple as: { copy: ..., copyItem: (item: MyType) => ({ ...item }) }

There is a complete example using a Person class on the demo page.

0
KGBR On

The trick was before calling this.dragulaService.dropModel(... i had to set the copy option:

this.dragulaService.find('DragItems').options.copy = true;
this.dragulaService.find('DragItems').options.copyItem = (item: any) => ({...item});