1

I'm adding childcomponents dynamically as shown here: https://plnkr.co/edit/iTG7Ysjuv7oiDozuXwj6?p=preview&preview

I changed the code slightly to this:

@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;
    }


I'm adding the component to the dom after clicking on a button with this function

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

so instead of creating the eventEmitters manually like this

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

I would like to do map over the outputs attribute of the childcomponent and create an eventEmitter for each output of the childcomponent to transmit the information one level higher. Something like this:

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)
       }

Is something like this possible at all. Does anybody know how to achieve something like this

Anbesa
  • 101
  • 1
  • 7
  • You can iterate over all properties and filter on `instanceof EventEmitter`, I would assume. – Ingo Bürk Feb 19 '21 at 14:33
  • This post might help you : https://stackoverflow.com/questions/66229575/what-is-the-correct-way-to-call-a-method-of-the-host-or-parent-component-from-a/66229870#66229870 – OLO Feb 19 '21 at 15:59

0 Answers0