cdk Drag and drop of an image from one div to another in angular

3k views Asked by At

I have created two divs one containing an image and other is empty. i want to drag and drop that image from one div to another. Here I'm using cdk drag and drop and cdkDragFreeDragPosition property but I'm not satisfied with this as I'm looking for something more like this effect

<div class="example-container">
  <h1>From</h1>

  <div class="example-list1"
  id = "pic1">
    <div cdkDrag class="example-box" [cdkDragFreeDragPosition]="dragPosition">
      <img width="350px" height="250px" src="https://material.angular.io/assets/img/examples/shiba2.jpg" alt="Photo of a Shiba Inu">
    </div>
  </div>
</div>


<div class="example-container">
  <h1>To</h1>
  <div class="example-list"
  id = "pic2">
    <div cdkDrag class="example-box">
     
    </div>
  </div>
</div>

ts:
dragPosition = {x: 0, y: 0};
1

There are 1 answers

1
Eliseo On

cdkDrag is not Magic. If you can Drag "something" in a "place" you need use two cdkDropList. When we has two cdkDropList you can think about this as two divs with two arrays

<div *ngFor="let item of arrayOne">
  {{item}}
</div>
<div *ngFor="let item of arrayTwo">
  {{item}}
</div>

cdk-drag allow interchange the elements from array-one to array-two. Yes, instead make something like

<button (click)="interchange(index1,index2)">interchange</button>
interchange(index1,index2)
{
   const element=this.arrayOne.splice(index1,1)
   this.arrayTwo.splice(index2,0,element[0])
}

We make dragging

So, you need two cdkDropList, inside the cdkDropList you can use a *ngFor in a div, and each div is a cdkDrag, or use an unique element. Again with the example of two divs, we can has something like

<div cdkDropList ...>
  <div *ngFor="let item of arrayOne" cdkDrag>
    {{item}}
  </div>
<div>

<div cdkDropList ...>
  <div *ngFor="let item of arrayTwo" cdkDrag>
    {{item}}
  </div>
<div>

But a cdkDropListis not necesary was a list. You can has a cdkDropList with an unique element

<div cdkDropList ...>
  <div cdkDrag>
    {{itemOne}}
  </div>
<div>

<div cdkDropList ...>
  <div cdkDrag>
    {{itemTwo}}
  </div>
<div>

In this case, the interchange is simply

 itemTwo={...itemOne}
 itemOne=null