将@Output EventEmitter 动态添加到 Angular 组件

问题描述

我正在动态添加子组件,如下所示:https://plnkr.co/edit/iTG7Ysjuv7oiDozuXwj6?p=preview&preview

我稍微修改了一下代码

@ViewChild('parent',{ read: ViewContainerRef })
    target: ViewContainerRef;
    private componentRef: ComponentRef<any>;

    constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
    ngOnInit() {
        this.childComponent = this.componentFactoryResolver.resolveComponentFactory(this.type);
    }
    createComponent(vCref: ViewContainerRef,input): ComponentRef<any> {
        // vCref is needed cause of that injector..
        let injector = Injector.create([]);

        // create component without adding it directly to the DOM
        let comp = this.childComponent.create(injector);
        // add inputs first !! otherwise component/template crashes ..
        comp.instance.input = input;
        // all inputs set? add it to the DOM ..
        vCref.insert(comp.hostView);

        return comp;
    }


单击具有此功能的按钮后,我正在将组件添加到 dom

addElement() {
            this.componentRef = this.createComponent(this.target,this.input);
            this.componentRef.instance['onClose'].subscribe((a) => this.onEvent.emit(a));
        
    }

所以不要像这样手动创建 eventEmitters

 this.componentRef.instance['onClose'].subscribe((a) => this.onEvent.emit(a));

我想对子组件的输出属性进行映射,并为子组件的每个输出创建一个 eventEmitter 以传输更高级别的信息。 像这样:

this.childComponent.outputs.map(output=>{
     'create new EventEmitter with the name "output.propName"'
      this.componentRef.instance[output.propName]).subscribe(a => {
                  this."output.propName".emit(a)
       }

这样的事情有可能吗。有谁知道如何实现这样的事情

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)