拖放动态添加的组件-角度7

时间:2020-04-17 06:54:18

标签: javascript angular angular-material-7 cdk

我正在使用viewRef和组件工厂解析器添加组件动态,我可以实现动态创建。现在,我需要为每个单独添加的组件添加拖放功能

<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文件用于添加组件

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);
  }

子组件中的代码

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

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

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

放置方法

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

    console.log(event);

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

现在我可以拖动组件了。但这适用于整个div。我需要拖放单个块 注意:我没有使用ngFor

Example depiction 预先谢谢大家:)

0 个答案:

没有答案