Paul
Paul

Reputation: 1355

Add event handler to dynamically loaded component

I have two components: workflow and block. The block components are loaded dynamically into workflow using a directive and the ComponentFactory.

The block component contains a button and I want to emit an event to the parent (workflow) when the button was clicked, therefore I added @Output('onDelete') onDelete = new EventEmitter<boolean>() in BlockComponent in order to be able to emit the event.

The problem which I encounter is adding the event handler on the <app-block>. I tried to add it using document.getElementsByTagName('app-block').addEventListener('(onDelete)', 'blockDeleted()') but it's not working.

workflow.component.html

<div clas="mainContent">
  <ng-template appWorkflowDirective></ng-template>
</div>

workflow.component.ts

private createNewBlockComponent(event, object): void {
   const componentFactory = this.componentFactoryResolver.resolveComponentFactory(BlockComponent);
   const componentRef = this.workflowsDirective.viewContainerRef.createComponent(componentFactory);

   (<BlockComponent>componentRef.instance).position = new BlockPosition(event.layerX, event.layerY) ;
}

I'm looking for the same behavior as in this example from angular

Upvotes: 3

Views: 5422

Answers (1)

No&#233;mi Sala&#252;n
No&#233;mi Sala&#252;n

Reputation: 5026

Generic example

const componentFactory = this.componentFactoryResolver.resolveComponentFactory(BlockComponent);

const componentRef = this.viewContainerRef.createComponent(componentFactory);

const blockInstance = componentRef.instance as BlockComponent;

blockInstance.onDelete.subscribe(() => {
    this.blockDeleted();
});

Specific example for this question

private createNewBlockComponent(event, object): void {
   const componentFactory = this.componentFactoryResolver.resolveComponentFactory(BlockComponent);
   const componentRef = this.workflowsDirective.viewContainerRef.createComponent(componentFactory);

   (<BlockComponent>componentRef.instance).position = new BlockPosition(event.layerX, event.layerY) ;

   (<BlockComponent>componentRef.instance).onDelete.subscribe(() => {
      this.blockDeleted();
   }) ;
}

Upvotes: 10

Related Questions