How to use Output in dynamically created component

后端 未结 2 1992
没有蜡笔的小新
没有蜡笔的小新 2021-02-01 01:29

I am using this technique to dynamically create component:

import {
 Component, Input, ViewContainerRef, ViewChild, ReflectiveInjector,    ComponentFactoryResolv         


        
相关标签:
2条回答
  • 2021-02-01 02:13

    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 => ...);
    
    0 讨论(0)
  • 2021-02-01 02:22

    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>
    
    0 讨论(0)
提交回复
热议问题