向动态加载的组件添加事件处理程序

时间:2018-02-28 19:28:46

标签: angular typescript dynamically-generated eventemitter

我有两个组件:workflowblockblock组件使用workflowdirective动态加载到ComponentFactory

block组件包含一个按钮,我想在点击按钮时向父级(workflow)发出一个事件,因此我在@Output('onDelete') onDelete = new EventEmitter<boolean>()中添加了BlockComponent为了能够发出事件。

我遇到的问题是在event handler上添加<app-block>。 我尝试使用document.getElementsByTagName('app-block').addEventListener('(onDelete)', 'blockDeleted()')添加它,但它不起作用。

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) ;
}

我正在寻找与角色

中此example相同的行为

1 个答案:

答案 0 :(得分:7)

通用示例

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

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

const blockInstance = componentRef.instance as BlockComponent;

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

此问题的具体示例

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();
   }) ;
}