I am using this technique to dynamically create component:
import {
Component, Input, ViewContainerRef, ViewChild, ReflectiveInjector, ComponentFactoryResolv
Your factory:
factory.create(injector);
will return an ComponentRef object, and with this object you can access that component itself.
You could subscribe to that event via:
component.instance.visibility.subscribe(v => ...);
Just subscribe the output event like this
@ViewChild('yourComponentRef', { read: ViewContainerRef }) container: ViewContainerRef;
// Reference for dynamic component
private _ref;
constructor(
private _cfr: ComponentFactoryResolver){ }
public addDynamicComponent() {
const comp =
this._cfr.resolveComponentFactory(<YOUR_DYNAMIC_COMPONENT_HERE>);
this._ref = this.container.createComponent(comp);
// Input to dynamic component
this._ref.instance.inputVarHere = [1, 2, 3];
// Handles output event, just emit your output here
this._ref.instance.outputEventHere.subscribe(data => {
console.log(data);
});
}
public removeDynamicComponent() {
this._ref.destroy();
}
In your html file
<!-- Section to load dynamic component -->
<div #yourComponentRef></div>