2

I have an Angular4 component that creates dynamically many children as soon as the user press a plus button. The child component has an input select that must send an information to the parent component after option selection.

Children components are being created by ComponentFactoryResolver as the section below

let componentFactory = this.componentFactoryResolver.resolveComponentFactory(MyComponent);
let viewContainerRef = this.anchor.viewContainerRef;
viewContainerRef.createComponent(componentFactory);

The child component has an output using EventEmitter, but nothing happens when the application runs.

I've tried without dynamic creation and works fine.

I searched many examples, but none of them consider angular4 or communication between parent and dynamic created child.

Fabrizio
  • 89
  • 1
  • 1
  • 8

1 Answers1

2

Try this:

let componentFactory = this.componentFactoryResolver.resolveComponentFactory(MyComponent);
let viewContainerRef = this.anchor.viewContainerRef;

const dynamicComponentInstance = viewContainerRef.createComponent(componentFactory).instance;
dynamicComponentInstance['childEventEmitter'].subscribe((eventEmitter) => {
  console.log(eventEmitter)
});

childEventEmitter is a variable name which you emit from the child component.

Dale K
  • 25,246
  • 15
  • 42
  • 71
張柏欽
  • 21
  • 3