Angular 7-向动态创建的组件添加拖放行为 [英] Angular 7 - Add drag and drop behaviour to dynamically created components

查看:57
本文介绍了Angular 7-向动态创建的组件添加拖放行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在SO上提出的上一个问题的延续: 在组件选择器声明时向其添加指令-角度7

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.

在上一个问题中,我尝试使用Angular-Material,但意识到由于将"cdkDrag"指令添加到组件的选择器标记以及cdkDropList的事实,可能无法将其用于组件和cdkDrag可能需要在同一模板中.

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.

我在模板中有一个div,

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?

谢谢.

推荐答案

更新

虽然这对于一种单一类型的组件可以正常工作,但是如果您需要使用不同的动态类型的组件,请阅读下面的Chaitanya Bangera的注释!

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!

应该使用类似的东西(CmpComponent将是您要插入的组件):

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>

这篇关于Angular 7-向动态创建的组件添加拖放行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆