Ad

Angular 7 - Add Drag And Drop Behaviour To Dynamically Created Components

This is in continuation of the previous question I asked on SO: Add directives to component selector when it is declared - Angular 7

I am dynamically creating components on a button click. The components are displayed one below another in a list like manner. I want to introduce drag-drop behaviour so that the user can rearrange the components after creating them.

In the previous question, I tried using Angular-Material, but realised it might not be possible to use it for components, due to the issue of adding "cdkDrag" directive to the component's selector tag, and the fact that the cdkDropList and cdkDrag might need to be in the same template.

I have a div as such in the template:

<div cdkDropList style="margin: 20px" (cdkDropListDropped)="drop($event)">
    <div #container></div>
</div>

And, I am creating custom components as follows:

@ViewChild('container', {read: ViewContainerRef})
  container: ViewContainerRef;

const childComponent = this.componentFactoryResolver.resolveComponentFactory(CustomComponent);
const component = this.container.createComponent(childComponent);

This works fine. Is it possible at all to create draggable dynamically created components?

Thank you.

Ad

Answer

Update

While this works fine with one single type of component, if you need to use different dynamic types of components, read Chaitanya Bangera's comment down below!

Original Comment

Should work with something like this (CmpComponent would be your component that you want to insert):

  components: CmpComponent[];

const childComponent = this.componentFactoryResolver.resolveComponentFactory(CustomComponent);
this.components.push(childComponent);


drop(event: CdkDragDrop<CmpComponent[]>) {
  moveItemInArray(this.components, event.previousIndex, event.currentIndex);
}
<div cdkDropList style="margin: 20px" (cdkDropListDropped)="drop($event)">
    <div cdkDrag *ngFor="let cmp of components">
        <app-cmp></app-cmp>
    </div>
</div>

Ad
source: stackoverflow.com
Ad