0

The requirement that I am having is to generate a component that can access and render the child components that are added to it in the markup.

HTML

<my-parent>
    <span>hey</span>
    <span>heck</span>
</my-parent>

Rendered HTML

<div>
    <span>before</span>
    <span>hey</span>
    <span>after</span>
    <br />
    <span>before</span>
    <span>heck</span>
    <span>after</span>
</div>

I was not able to find any resource to help me with it. This is a behavior similar to how mat select interacts with mat options.

Shashank Vivek
  • 16,888
  • 8
  • 62
  • 104
Sachith Rukshan
  • 340
  • 6
  • 24

1 Answers1

1

Use ng-content with select as demoed here

<my-parent>
  <span a>hey</span>
    <span b>heck</span>
</my-parent>
  <div>
    <span>before - </span>
    <ng-content select="[b]"></ng-content>
    <span> - after</span>
    <br />
    <span>before - </span>
    <ng-content select="[a]"></ng-content>
    <span> - after</span>
</div>
Shashank Vivek
  • 16,888
  • 8
  • 62
  • 104
  • what if I had spans in a ngfor. – Sachith Rukshan Mar 29 '20 at 05:59
  • 1
    @SachithRukshan : I also has this question for which I even put bounty. Take a look at https://stackoverflow.com/questions/49988436/why-ng-content-selector-is-not-working-inside-ngfor . Let me know if it helped – Shashank Vivek Mar 29 '20 at 11:58
  • @SachithRukshan : Here is another link which I answered for something somewhat similar . https://stackoverflow.com/questions/60761677/how-to-render-a-content-inside-directive-at-various-places/60762239#60762239 – Shashank Vivek Mar 29 '20 at 12:00