2

I want to create the following component:

<my-component [attr1]="attr1" [attr2]="attr2">
</my-component>  

This is fine, but I want in this component to render any kind of template, so I need something like this:

<my-component [attr1]="attr1" [attr2]="attr2">
    <my-component-template>
        // Here comes the template for my-component component
    </my-component-template>
</my-component>  

Any sample of how to do this? I couldn't find any reference.

DAG
  • 2,460
  • 5
  • 33
  • 61
  • Where does the template come from? What does it contain (plain HTML, Angular bindings, Angular components, ...)? – Günter Zöchbauer Oct 10 '16 at 09:41
  • It can be anything. Mostly a complex HTML...I thought about innerHtml binding but this template might be to complex and that is why I want a child component that renders any kind of content – DAG Oct 10 '16 at 09:44
  • `my-cmp` and `my-cmp-template` are they both different components??? – micronyks Oct 10 '16 at 09:45
  • There is quite some difference about "anything". If it contains Angular stuff it needs to be compiled at runtime if it isn't compiled with the code. There are questions with answers about that. If it doesn't contain Angular stuff, you can pass the HTML like `[prop]="someHtml"` and then inside the component use whatever you want to add HTML to the DOM (create a DocumentFragment` and add it. – Günter Zöchbauer Oct 10 '16 at 09:46
  • Ok, so you mean is not possible to created a nest of components? I could do as you suggested, but that was not my question. If I do with property binding as suggested (and I already have this approach) this might look horrendous depending on how big the HTML of the content is, – DAG Oct 10 '16 at 10:08

1 Answers1

2

I think you're looking for <ng-content> or adding components using ViewContainerRef and ComponentFactoryResolver. I'm not able to find any useful examples on either of these in the official documentation though...

See <ng-content> used:

See dynamically adding components:

Graham
  • 7,431
  • 18
  • 59
  • 84
martin
  • 93,354
  • 25
  • 191
  • 226