Search code examples
angularangular-materialangular-cdkangular-cdk-drag-drop

Angular 13 - Drag and drop is not working with ngFor -json array


I'm giving my very 1st attempt with Angular material CDK drag and drop for one my user story.

I don't understand why array of object is not working in cdk drag and drop

Argument of type 'CdkDragDrop<{ id: number; imgSrc: string; name: string; }[], any, any>' is not assignable to parameter of type 'CdkDragDrop<string[], string[], any>'. The types of 'container.data' are incompatible between these types. Type '{ id: number; imgSrc: string; name: string; }[]' is not assignable to type 'string[]'.

I'm trying to drag image from below data source

items = [
    {
      id: 0,
      imgSrc: 'https://via.placeholder.com/150/0000FF/808080',
      name: 'Color B',
    },
    {
      id: 1,
      imgSrc: 'https://via.placeholder.com/150/FF0000/FFFFFF',
      name: 'Color R',
    },
    {
      id: 2,
      imgSrc: 'https://via.placeholder.com/150/FFFF00/000000',
      name: 'Color L',
    },
  ]; // drag from this source

Drop it to my empty location

basket = [] // drop items here

my scenario is to load API response in item=[] and do drag and drop it to my basket = [] then submit the reactive form.

I changed this official straight forward example as per my requirement. But getting above mentioned error. Since its very first start I don't know how to fix this issue.

Kindly help me on this.

Thanks to all

Facing below issue in my local even after imported dragNdrop module facing in my local


Solution

  • I have fixed your stackblitz sample. See here.

    First, define Item interface.

    interface Item {
      id: number;
      imgSrc: string;
      name: string;
    }
    

    Then you have to define items and baskets as Item[].

    items: Item[] = [
      :
    ];
    
    basket: Item[] = [];
    

    And your drop argument should be Item[].

    drop(event: CdkDragDrop<Item[]>) {
      :
    }