首页 > 解决方案 > 声明时向组件选择器添加指令 - Angular 7

问题描述

我正在学习 Angular,并通过单击按钮动态创建组件。我正在尝试使用 Angular Material 的拖放功能来拖动这些创建的组件以对其进行排序。我的基本组件 html 中有以下代码:

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

Typescript代码有以下代码:

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

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

到目前为止,我已经设法动态地创建组件,并设法使用指令“cdkDropList”将它们作为 div 的子级。

我无法做的是获取使用在其元素名称中声明的 cdkDrag 指令创建的组件。例如:

<app-CustomComponent cdkDrag>

我正在研究 @HostBinding 并可以创建具有属性的组件。无法弄清楚如何使用它来声明指令。我确信我错过了一些明显的东西,但到目前为止我被卡住了。请帮忙。

标签: javascriptangularangular-materialangular2-directivesangular-components

解决方案


推荐阅读