Search code examples
angularangulardraganddroplists

How to create list of Component for drag and drop CDK angular


I trying to create drag and drop to list Components with drag and drop CDK of angular, like below, but the Components are not displayed properly.

App.component.ts

import { RightSideCombinedComponent } from './right-side.component';
import { LeftSideComponent } from './left-side.component';
@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

innerComponenets: Array<any> = [
  RightSideCombinedComponent,
  LeftSideComponent,
  ];
constructor() { }

  ngOnInit(): void {
  }

  

  drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.innerComponenets, event.previousIndex, event.currentIndex);
  }

<div cdkDropList cdkDropListOrientation="horizontal" class="example-list" (cdkDropListDropped)="drop($event)">
            <div class="example-box" *ngFor="let item of innerComponenets"  cdkDrag>
                {{item}}
                </div>

the screen displayed (The code of the components is displayed instead of the display of the components): Before drag and drop: enter image description here

Drag and drop: enter image description here

After drag and drop: enter image description here

Does anyone know how to do it right?


Solution

  • array=[0,1];
    
    <div cdkDropList cdkDropListOrientation="horizontal" class="example-list"
          (cdkDropListDropped)="drop($event)">
      <div class="example-box" *ngFor="let item of array" cdkDrag>
          <app-left-side *ngIf="item==0"></app-left-side>
          <app-right-side *ngIf="item==1"></app-right-side>
      </div>
    </div>
    

    a stackblitz

    See that you only interchange the elements of the array [0,1]. If this array who say to Angular which component must show in first time

    NOTE: This tecnica only is util if we don't store data in the components, think that each drop the components are new and initializeted