Angular CDK Drag and drop, Handling multiple drag elements

161 views Asked by At

Here i have this draggable list that have to be dragged and dropped to every div that is generated on the click of add button. So till now what i have achieved is, iam able to drag and drop to the first div and not the other generated div. Is there any solution anyone can suggest ? html:

<div class="drag-column">
    <div class="field-list text-center">
    <p>Drag and Drop the column</p>
    <div cdkDropList #newTodoList="cdkDropList" [cdkDropListData]="section.newTodo"
        [cdkDropListConnectedTo]="getConnectedLists(i)" class="example-list"
        (cdkDropListDropped)="newDrop($event, i)">
        <div class="example-box" *ngFor="let item of section.newTodo" cdkDrag [cdkDragData]="item">
        {{ item }}
        </div>
    </div>
    </div>

    <div class="input-column" *ngFor="let input of inputColumns; let i = index">
    <b>A{{ i + 1 }}</b>
    <div cdkDropList [cdkDropListData]="input.columnData"
        [cdkDropListConnectedTo]="getConnectedLists(i)" class="example-list" (cdkDropListDropped)="newDrop($event, i)">
        <div class="example-box" *ngFor="let item of input.columnData" cdkDrag [cdkDragData]="item">
        {{ item }}
        </div>
    </div>
    </div>

    <button class="add-column" (click)="addInputColumn()">add</button>
</div>

TS:

addInputColumn() {
    const newInputColumn: { columnData: string[] } = { columnData: [] };
    this.inputColumns.push(newInputColumn);
  }

newDrop(event: CdkDragDrop<string[]>, divIndex: number) {
    console.log('currentDiv.columnData:', this.inputColumns[divIndex].columnData);
    console.log('event:', event);
    const currentDiv = this.inputColumns[divIndex];
  
    const targetColumn = currentDiv.columnData;
    const draggedItem = event.item.data as string;
    const sourceList = event.previousContainer.data as string[];
  
    // Remove the dragged item from the source list
    const indexToRemove = sourceList.indexOf(draggedItem);
    if (indexToRemove !== -1) {
      sourceList.splice(indexToRemove, 1);
    }
  
    // If the target column already has an item, replace it
    if (targetColumn.length > 0) {
      const previousItem = targetColumn[0];
      targetColumn.splice(0, 1, draggedItem);
      sourceList.push(previousItem);
    } else {
      targetColumn.push(draggedItem);
    }
  }

  getConnectedLists(index: number) {
    return [`newTodoList${index}`, ...this.inputColumns.map((_, i) => `newInputList${i}`)];
  }

enter image description here

0

There are 0 answers