4

I'm creating a component through the ComponentFactoryResolver dynamically. But can't apply any directive to it.

ComponentCreation

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

Tried directive instantiation in two places -

Component.ts

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

Or

Component Creation

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

Also tried calling the NgOnInit method, Object creation in SetTimouts. No luck. The end result is very different from the directive-in-template way. The directive is added as a attribute-value pair to the element.

How can a directive be added to a dynamic component ?

If it can't be done, do you know of good practices about adding HostListeners, HostBinding dynamically to a component ? If keeping it inside Angular becomes too cumbersome, I might remove Angular APIs altogether from this dynamic component creations and do it in DOM.

nomanbinhussein
  • 282
  • 5
  • 11

0 Answers0