Sachith Rukshan
Sachith Rukshan

Reputation: 351

Accessing child Components inside the parent component's html element

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.

Upvotes: 0

Views: 61

Answers (1)

Shashank Vivek
Shashank Vivek

Reputation: 17504

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>

Upvotes: 1

Related Questions