[英]Add event handler to dynamically loaded component
I have two components: workflow
and block
. 我有两个组件:
workflow
和block
。 The block
components are loaded dynamically into workflow
using a directive
and the ComponentFactory
. 使用
directive
和ComponentFactory
将block
组件动态加载到workflow
。
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. block
组件包含一个按钮,我想在单击按钮时向父( workflow
)发出一个事件,因此我在BlockComponent
中添加了@Output('onDelete') onDelete = new EventEmitter<boolean>()
以便能够发出事件。
The problem which I encounter is adding the event handler
on the <app-block>
. 我遇到的问题是在
<app-block>
上添加event handler
。 I tried to add it using document.getElementsByTagName('app-block').addEventListener('(onDelete)', 'blockDeleted()')
but it's not working. 我尝试使用
document.getElementsByTagName('app-block').addEventListener('(onDelete)', 'blockDeleted()')
添加它document.getElementsByTagName('app-block').addEventListener('(onDelete)', 'blockDeleted()')
但它不起作用。
workflow.component.html workflow.component.html
<div clas="mainContent">
<ng-template appWorkflowDirective></ng-template>
</div>
workflow.component.ts 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 我正在寻找与此示例中相同的行为
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();
}) ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.