angularangular-materialangular-cdkangular-dragdrop

Stuck more than 2 hrs Angular CDK Drag and Drop - Not able to drop the item in the location


Am Struggling lot to complete my task as newly started into Angular CDK DragnDrop. When trying to drag the image item and drop into location, I got Cannot read properties of undefined (reading 'length') .

Not sure this is because of different Interface against Angular DragnDrop CDK

  drop(event: CdkDragDrop<any>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    } else {
      transferArrayItem(
        event.previousContainer.data, 
        event.container.data,                              // getting undefined here
        event.previousIndex,
        event.currentIndex
      );

      console.log(
        'transferArrayItem',
        event.container.data.colorways
      );

      const formArry = this.myDivName;
      formArry.insert(0, this.fb.control(event.container.data));
    }
  }

does event.container.data, pointing to drop location or source location?

My stackblitz


Solution

  • Here you go

    /* Add initial empty data */
    imgSource: Pokedex = {
      colorways: [],
      count: 0,
    };
    
    drop(event: CdkDragDrop<any>) {
    ...
    else {
     transferArrayItem(
       event.previousContainer.data,
       event.container.data, //remove colorways, event.container.data?.colorways,
       event.previousIndex,
       event.currentIndex
     );
    }
    
    <!-- Left container -->
    [cdkDropListData]="colorways" <!-- Wrong -->
    [cdkDropListData]="colorways.colorways" <!-- Right -->
    
    <!-- Right Container -->
    [cdkDropListData]="imgSource" <!-- Wrong -->
    [cdkDropListData]="imgSource?.colorways" <!-- Right -->
    

    Working Stackblitz