微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决将@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 举报,一经查实,本站将立刻删除。