Getting nested element into ng-content

104 views Asked by At

I try to get the all the <pane /> with one <ng-content />.

One <pane /> is directly in the root DOM of the parent element, and the other one is inside a <div></div>

Parent Component HTML:

<tab style="display: flex; flex-direction: column">
   <pane id="1">Pane 1</pane>
   
   <div>
     <pane id="2">Pane 2</pane>
   </div>
</tab>

Child Pane Component HTML:

Pane in ng-content select="pane" 
<ng-content select="pane" />

<br/>
Others panes:
<ng-content />

Here is the result:

Pane in ng-content select="pane" Pane 1

Others panes: Pane 2

My first <ng-content /> doesn't catch the nested <pane /> and it's goes the the second one.

Is there a way to catch all <pane /> in the first <ng-content /> ?

Here my example : https://stackblitz-starters-j5xukj.stackblitz.io Doc related to : https://angular.dev/api/core/ContentChildren?tab=usage-notes

1

There are 1 answers

1
NgDaddy On

Use class as a selector and it should work:

https://stackblitz.com/edit/stackblitz-starters-cs5uqo?file=src%2Fmain.ts

@Component({
  selector: 'tab',
  standalone: true,
  imports: [Pane, CommonModule],
  template: `
    Pane in ng-content select=".pane-container" 
    <ng-content select=".pane-item" ></ng-content>
    ----------
    <br/>
    Others panes:
    <ng-content ></ng-content>
    ----------
  `,
})
export class Tab {}

@Component({
  selector: 'example-app',
  standalone: true,
  imports: [Tab, Pane, CommonModule],
  template: `
    <tab style="display: flex; flex-direction: column">
      <pane class="pane-item" id="1">Pane Item 1</pane>
      <pane class="pane-item" id="2">Pane Item 2</pane>      
      <div class="pane-container">
        <pane id="1">Pane 1</pane>
        <pane id="2">Pane 2</pane>
      </div>
    </tab>
  `,
})
export class ContentChildrenComp {}