How to use Output in dynamically created component

后端 未结 2 1991
没有蜡笔的小新
没有蜡笔的小新 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: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();
        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

    
    

提交回复
热议问题