Search code examples
javascripthtmlweb-component

How to choose where children of a custom element will be located?


Hello I have a custom webcomponent and I want to decide where to put the children inserted by the upper (parent) element.

File of upper html element using my custom component:

  <custom-component>
    <custom-component2></custom-component2>
  </custom-component>

File describing custom-component inside structure:

<h5>title</h5>
 <p>paragraph</p>

Result in DOM:

  <custom-component>
        <custom-component2></custom-component2>
       <h5>title</h5>
       <p>paragraph</p>
 </custom-component>

What I want:

  <custom-component>
       <h5>title</h5>
       <p>paragraph</p>
        <custom-component2></custom-component2>
 </custom-component>

How can I choose where to put the content like ng-content in Angular or props.children in React? I am building a custom webcomponent library. Thank you


Solution

  • You can use slots for displaying parent oriented content. Furthermore, you can organise this by named slots.

    This works in Angular with Content Projection.

    You can give these ng-content names.