0

In React, I could easily do the following to nest two components whose actual type was not known until runtime, and whose class types were supplied as props:

render() {
  const FirstComponent = this.props.comp1;
  const SecondComponent = this.props.comp2;

  return (
    <FirstComponent>
      <SecondComponent></SecondComponent>
    </FirstComponent>
  );
}

How would do I do the equivalent in Angular? The Angular documentation explains how to create a dynamic component as a view child of itself, but not how a component can set a dynamic component as the content child of another dynamic component.

Basically, I want to be able to have the following:

<my-component [comp1]="FirstComponentClass" [comp2]="SecondComponentClass"></my-component>

And at runtime, produce the equivalent component hierarchy:

<my-component>
    <first-component>
        <second-component></second-component>
    </first-component>
</my-component>

How would I implement my-component?

Jon Rimmer
  • 12,064
  • 2
  • 19
  • 19
  • To tell you the truth, there's no way to make it work out-of-the-box. You will need to combine Dynamic Components and Transclusion. Here are good articles to start with: https://toddmotto.com/transclusion-in-angular-2-with-ng-content and https://medium.com/front-end-hacking/dynamically-add-components-to-the-dom-with-angular-71b0cb535286 . should instantiate both component 1 and 2 inside each other. Component 1 should support transclusion. – Vitalii Chmovzh Feb 10 '18 at 15:43
  • @VitaliiChmovzh But how can I "instantiate both component 1 and 2 inside each other"? All the dynamic examples I've seen, including those you linked, use a ViewContainerRef to insert a single component into the view. How do I insert both component 1 and 2 in a way that puts 2 inside of 1, so that it transcludes? – Jon Rimmer Feb 10 '18 at 16:02
  • That's what i'm talking about. You should make your own custom implementation. There definitely no easy way :( – Vitalii Chmovzh Feb 10 '18 at 16:05
  • I don't see *any* way, easy or hard, even with a custom implementation. Many there is a private Angular API that can do this, but I can't find anything in the public API that can help. – Jon Rimmer Feb 10 '18 at 16:10
  • Then you probably need to look on this problem from a different angle. Maybe you don't need such approach. What are you trying to achieve? – Vitalii Chmovzh Feb 10 '18 at 16:11
  • I'm trying to create a library that can take an arbitrary list of 3rd-party components (e.g. not authored or controlled by me), and nest them inside each other. The only thing I know for sure about them is that they support transclusion. The idea is that each component wraps those inside it to decorate them with some additional UI. – Jon Rimmer Feb 10 '18 at 16:15

0 Answers0