9

I have three components: Panel, PanelGroup (ul) and PanelItem (li):

Panel:

@Component({
selector: "panel",
directives: [PanelGroup,PanelItem],
template: `
  <panel-group>
    <ng-content select="panel-item"></ng-content>
  </panel-group>
`})

export default class Panel {}

PanelGroup:

@Component({
selector: "panel-group",
directives: [forwardRef(() => PanelItem)],
template: `
  <ul>
    <ng-content></ng-content>
  </ul>`
})

export default class PanelGroup {
  @ContentChildren(forwardRef(() => PanelItem)) items;

  //I need to access children here and modify them eventually:
  ngAfterContentInit() {
    console.log(this.items.toArray()); //the array is always empty
  }
}

PanelItem:

@Component({
selector: "panel-item",
directives: [forwardRef(() => PanelGroup)],
template: `
  <li>
    <span (click)="onClick()">
        {{title}}
    </span>
    <panel-group>
        <ng-content select="panel-item"></ng-content>
    </panel-group>
  </li>`
})

export default class PanelItem {
  @Input() title = 'SomeTitle';
}

As seen in the above example I try to get the content children inside the PanelGroup component, however the collection is always empty. Also tried to add selector to the 'ng-content' inside it - in this case the children are never rendered which is bit weird.

Am I missing something?

Here is plunk:

Pierre Arlaud
  • 4,040
  • 3
  • 28
  • 42
Vladimir Iliev
  • 1,871
  • 16
  • 26

2 Answers2

19

Use descendants: true:

@ContentChildren(forwardRef(() => PanelItem), {descendants: true}) items;

See also angular 2 / typescript : get hold of an element in the template

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

I am having a similar issue but it seems this one can also be solved by removing the select option from the panel-item. I assume since select='panel-item' is looking for only content but there is a Nested Object as content. If you remove the restriction (in the plunk example) it shows it.