Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@ContentChildren is not being populated when parent render items using ng-content

Tags:

angular

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:

  • demo
like image 857
Vladimir Iliev Avatar asked May 31 '16 20:05

Vladimir Iliev


1 Answers

Use descendants: true:

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

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

like image 141
Günter Zöchbauer Avatar answered Nov 02 '22 22:11

Günter Zöchbauer