1

I am adding component dynamic using viewRef and component factory resolver, I could achieve the dynamic creation. Now i need to add a drag and drop feature to the every component added individually

<button type="button" (click)="createComponent()">
 Create Widget
</button>
<div cdkDropList (cdkDropListDropped)="drop($event)" [cdkDropListData]="components" >
  <div cdkDrag>
      <ng-container #container ></ng-container>
  </div>
</div>

ts file for adding component

createComponent() {
    let componentFactory = this.componentFactoryResolver.resolveComponentFactory(
      DemoComponent
    );
    let componentRef: ComponentRef<
      DemoComponent
    > = this.container.createComponent(componentFactory);
    let currentComponent = componentRef.instance;

    currentComponent.selfRef = currentComponent;
    currentComponent.type = ++this.index;
    currentComponent.type1 = ++this.heleloIndex;

    currentComponent.index = ++this.index;

    // prividing parent Component reference to get access to parent class methods
    currentComponent.compInteraction = this;

    // add reference for newly created component
    this.components.push(componentRef);
  }

Code in Child Component

<h1>Alert {{type}}</h1>
<h2>Alert {{type1}}</h2>

<button (click)="change()">change Widget data
</button>

<button (click)="removeMe(index)">Remove Widget
</button>
<hr>

The drop method

 public drop(event: CdkDragDrop<any[]>) {

    console.log(event);

    moveItemInArray(this.components, event.previousIndex, event.currentIndex);
    console.log(event.container.data);
  }

Now i can drag the component. But that is applying to whole div. I need to drag and drop individual blocks NOTE: I am not using ngFor

[Example depiction][1] [1]: https://i.stack.imgur.com/Vh1Q6.jpg

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Ranga
  • 21
  • 2
  • 1
    You need use the DragDrop service see https://material.angular.io/cdk/drag-drop/api#services. You inject the service in constructor and, when add an element, use the service to make dragable the element create (you make dragable `elementRef.naviteElement`) – Eliseo Apr 17 '20 at 08:51

0 Answers0