#StackBounty: #angular #typescript #angular-material #drag-and-drop Drag and drop custom static components using Angular Material CDK

Bounty: 50

With reference to Angular CDK Drag & Drop, I’m trying to create a simple dashboard with left sidebar and main content area. Both of these areas will contain unique custom components which need to be draggable and can be reordered within their contained area and transferred to another area.

For eg. Sidebar contains Comp and Comp1, then I can reorder them within that area and transfer them to the Main Content area.

From what I understand Angular Material CDK Drag & Drop only works with lists. Additionally the items in the lists have to be of similar type for them to be reordered/transferred.

Is there a way to utilize CDKDrag and CDKDropList for static items rather than items in an array? I’m not able to reorder or transfer custom components to a different drop lists.

I’ve create a sample project: https://stackblitz.com/edit/ng-mat-dnd
Demo: https://ng-mat-dnd.stackblitz.io/


<div class="example-container">

    <div cdkDropList #sidebarList="cdkDropList" [cdkDropListData]="sidebar" cdkDropListConnectedTo="[mainList]"
        class="example-list" (cdkDropListDropped)="drop($event)">
        <div class="example-box" cdkDrag>
            <app-demo-comp-2 [btn]=2></app-demo-comp-2>
        <div class="example-box" cdkDrag>
            <app-demo-comp [ddn]=2></app-demo-comp>
        <div class="example-box" cdkDrag>
            <app-demo-comp-3 [txt]=3></app-demo-comp-3>

<div class="example-container">

    <div cdkDropList #mainList="cdkDropList" [cdkDropListData]="main" cdkDropListConnectedTo="[sidebarList]"
        class="example-list" (cdkDropListDropped)="drop($event)">
        <div class="example-box" cdkDrag>
            <app-demo-comp [ddn]=1></app-demo-comp>
        <div class="example-box" cdkDrag>
            <app-demo-comp-2 [btn]=3></app-demo-comp-2>


import { Component, OnInit, ViewChildren, QueryList } from '@angular/core';
import { CdkDragDrop, moveItemInArray, transferArrayItem, CdkDrag } from '@angular/cdk/drag-drop';

  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
export class AppComponent  {  

  @ViewChildren(CdkDrag) draggables: QueryList<CdkDrag>;

  constructor() { }

  ngOnInit() { }

  ngAfterViewInit() {
    this.sidebar = [this.draggables.toArray()[0], this.draggables.toArray()[1], this.draggables.toArray()[2]];
    this.main = [this.draggables.toArray()[4], this.draggables.toArray()[3]];

  drop(event: CdkDragDrop<any[]>) {
    if (event.previousContainer === event.container) {
      console.log('Same container');
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      console.log('Different containers');

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.