0

I am new to Angular. I want to implement drag and drop functionality in my angular 6 app. I came across a very good library "CDK".

I have successfully implemented functionality to transfer items between two lists. Both the lists are in same component.

Now I am working on separating out the list components. I have put droplist1 in list-a-component.html and its items array in list-a-component.html. Similarly for droplist2.

But it doesn't work. I can move items in lists but cant transfer from one to another.

On investigation found that when the html renders for both lists, the html is missing "ng-reflect-connected-to" value. Its null.

<div _ngcontent-c1="" cdkdroplist="" class="example-list cdk-drop-list" ng-reflect-connected-to="" ng-reflect-data="Get to work,Pick up groceries," id="cdk-drop-list-2">
MARKAND Bhatt
  • 2,428
  • 10
  • 47
  • 80

1 Answers1

3

If the droplist( Drop Zone) is in the different component then it is not straight forward. To make it work we need to create droplist in source component and destination component and connect two droplists using cdkDropListConnectedTo.

drag-source-componet.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-drag-source',
  templateUrl: './drag-source.component.html',
  styleUrls: ['./drag-source.component.css']
})
export class DragSourceComponent implements OnInit {
  data = [
    "apple",
    "boy",
    "cat",
    "dog",
    "elephant"
  ]
  constructor() { }

  ngOnInit() {
  }

}
.example-list {
  width: 500px;
  max-width: 100%;
  border: solid 1px #ccc;
  min-height: 60px;
  display: block;
  background: white;
  border-radius: 4px;
  overflow: hidden;
}
<p>
Drag Source 
</p>

<div id="source" cdkDropList [cdkDropListConnectedTo]="['destination']" class="example-list">
  <ul>
    <li cdkDrag [cdkDragData]="item" *ngFor="let item of data">
      {{ item }}
    </li>
  </ul>
</div>

drop-destination-componet.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-drop-destination',
  templateUrl: './drop-destination.component.html',
  styleUrls: ['./drop-destination.component.css']
})
export class DropDestinationComponent implements OnInit {
  data = []
  constructor() { }

  ngOnInit() {
  }

  drop(event) {
    this.data.push(event.item.data);
  }

}
.example-list {
  width: 500px;
  max-width: 100%;
  border: solid 1px #ccc;
  min-height: 60px;
  display: block;
  background: white;
  border-radius: 4px;
  overflow: hidden;
}
<p>
Destination Drop Zone
</p>

<div id="destination" class="example-list" style="height: 200px; border: 2px solid black" cdkDropList [cdkDropListConnectedTo]="['source']" (cdkDropListDropped)="drop($event)">
    <ul>
    <li *ngFor="let item of data">
      {{ item }}
    </li>
  </ul>
</div>

To see the complete solution pls visit stackblitz

pradeep gowda
  • 664
  • 7
  • 10