这是我在 SO 上提出的上一个问题的延续:在声明组件选择器时添加指令 - Angular 7 https://stackoverflow.com/questions/56072516/add-directives-to-component-selector-when-it-is-declared-angular-7
我通过单击按钮动态创建组件。这些组件以类似列表的方式依次显示。我想引入拖放行为,以便用户可以在创建组件后重新排列组件。
在上一个问题中,我尝试使用 Angular-Material,但意识到可能无法将其用于组件,因为向组件的选择器标记添加“cdkDrag”指令的问题,以及 cdkDropList 和 cdkDrag 可能会需要在同一个模板中。
我在模板中有一个这样的 div:
<div cdkDropList style="margin: 20px" (cdkDropListDropped)="drop($event)">
<div #container></div>
</div>
而且,我正在创建自定义组件,如下所示:
@ViewChild('container', {read: ViewContainerRef})
container: ViewContainerRef;
const childComponent = this.componentFactoryResolver.resolveComponentFactory(CustomComponent);
const component = this.container.createComponent(childComponent);
这很好用。是否有可能创建可拖动的动态创建的组件?
谢谢。
我通过使用 createComponent 方法动态生成组件并通过 ViewComponentRef 方法处理移动来解决这个问题:
容器.组件.html
<div cdkDropList (cdkDropListDropped)="drop($event)">
<ng-container #cmpContainer></ng-container>
</div>
容器.组件.ts
import {CdkDragDrop, moveItemInArray} from "@angular/cdk/drag-drop";
import {DynamicComponent} from './dynamic.component.ts';
@ViewChild('cmpContainer', {static: true, read: ViewContainerRef}) cmpContainer: ViewContainerRef;
components: ComponentRef<DynamicComponent>[] = [];
addComponent() {
const factory = this.cfr.resolveComponentFactory(DynamicComponent);
const component: ComponentRef<DynamicComponent> = this.cmpContainer.createComponent(factory);
this.components.push(component);
}
drop(event: CdkDragDrop<DynamicComponent[]>) {
this.cmpContainer.move(this.components[event.previousIndex].hostView, event.currentIndex);
moveItemInArray(this.components, prevIndex, currentIndex);
}
动态组件.html
<div cdkDrag>
<div cdkDragHandle></div>
</div>
- 在这种情况下,您可以直接通过组件数组访问组件实例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)