我正在通过ComponentFactoryResolver动态创建一个组件 . 但不能对它适用任何指令 .

ComponentCreation

const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
const componentInstance: ComponentRef<any> = viewContainerRef.createComponent(componentFactory);

尝试在两个地方进行指令实例化 -

Component.ts

@HostBinding('attr.hxDraggableElement') hxDraggableElement = new DraggableElementDirective(this.el, this.renderer);

要么

组件创建

componentInstance.instance.hxDraggableElement =
new DraggableElementDirective(componentInstance.instance.el,
  componentInstance.instance.renderer);
componentInstance.instance.hxDraggableElement.ngOnInit();

还尝试调用NgOnInit方法,在SetTimouts中创建对象 . 没运气 . 最终结果与模板中的指令方式非常不同 . 该指令作为属性 - 值对添加到元素中 .

How can a directive be added to a dynamic component ?

如果无法完成,您是否了解有关将HostListeners,HostBinding动态添加到组件的良好实践?如果将它保留在Angular中变得过于繁琐,我可能会从这个动态组件创建中完全删除Angular API并在DOM中执行 .