How to implement drag and drop between buttons and dynamic 2D array rows using Angular CDK?

Discussão em 'Angular' iniciado por Ajay, Setembro 13, 2024.

  1. Ajay

    Ajay Guest

    I’m working on an Angular component where I want to drag and drop items from a set of alphabet buttons into different rows of a 2D array (slotButtons). Each row should act as an independent drop target, and I want to be able to drop multiple items into different rows.

    Here’s a simplified version of my setup:

    I have an array alphabet that contains buttons representing alphabet items (e.g., ['a', 'b', 'c', ...]). I have a 2D array slotButtons where each sub-array represents a row, and I want to drop alphabet items into these rows.

    HTML

    <div class="container">
    <!-- Alphabet Buttons -->
    <div cdkDropList class="alphabet-list" [cdkDropListData]="alphabet" (cdkDropListDropped)="onAlphabetDrop($event)">
    <button *ngFor="let letter of alphabet" cdkDrag>{{ letter }}</button>
    </div>

    <!-- Slot Buttons -->
    <div *ngFor="let slot of slotButtons; let i = index">
    <div cdkDropList [cdkDropListData]="slotButtons" (cdkDropListDropped)="onDrop($event, i)" class="slot">
    <div *ngFor="let item of slot" cdkDrag>{{ item }}</div>
    </div>
    </div>
    </div>



    Component

    export class DragDropComponent {
    slotButtons = [
    [], // Row 1
    [], // Row 2
    [], // Row 3 (more rows can be added)
    ];

    alphabet = ['a', 'b', 'c', 'd', 'e'];

    onDrop(event: CdkDragDrop<string[]>, index: number) {
    if (event.previousContainer !== event.container) {
    transferArrayItem(
    event.previousContainer.data,
    event.container.data,
    event.previousIndex,
    event.currentIndex
    );
    }
    }

    onAlphabetDrop(event: CdkDragDrop<string[]>) {
    ...
    }
    }



    Functionality i wish to include

    How can I correctly implement drag-and-drop functionality for:

    Dragging alphabet items into the rows of slotButtons. Moving items between different rows within slotButtons?

    Continue reading...

Compartilhe esta Página