spartarn-07
spartarn-07

Reputation: 1

unable to perform drag and drop of div elements

Actually i have scenario like, i have four divs & i should able to swap the div squares ,means i can interchange the position of div with each other without any error.while doing so mycode is not working when i am generating the divs dynamically.if manually i am creating four div then the code is somewhat working.i have attached the stackblitz link. could some one please help me to fix this issue..

please go through this link > https://stackblitz.com/edit/angular-srvwgw

@HostListener('drop', ['$event'])

onDrop(event) { event.preventDefault();

var data = event.dataTransfer.getData("text");
//  event.dataTransfer.dropEffect = 'copy';
var div = document.getElementById(data);
var mynode = document.getElementById(event.target.id);

var clonedElement1 = div.cloneNode(true);
var clonedElement2 = mynode.cloneNode(true);

mynode.parentNode.replaceChild(clonedElement1, mynode);
div.parentNode.replaceChild(clonedElement2, div);

}

i should able to swap the position of div with each other div.

Upvotes: 0

Views: 110

Answers (1)

Andrew Allen
Andrew Allen

Reputation: 8002

This can be acheived through the use of Angular Drag and Drop cdkList

Create several cdkDropList's and set cdkDropListData via one-way binding to its own array in TS.

Through the hook (cdkDropListDropped)="drop($event)" you can switch items between the containers via transferArrayItem (see the API on Angular website).

In the stackblitz below I've used the following which displaces the element immediately below where the item is placed unless at the end in which it displaces the one just prior.

  drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      transferArrayItem(event.previousContainer.data,
                        event.container.data,
                        event.previousIndex,
                        event.currentIndex);

      // transfer next or prior if last
      if (event.currentIndex + 1 < event.container.data.length) {
        transferArrayItem(event.container.data,
                    event.previousContainer.data,
                    event.currentIndex+1,
                    event.previousIndex);
      } else {
        transferArrayItem(event.container.data,
                    event.previousContainer.data,
                    event.currentIndex-1,
                    event.previousIndex);  
      }

    }

https://stackblitz.com/edit/angular-nxrupb

Upvotes: 1

Related Questions