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:
Use descendants: true
:
@ContentChildren(forwardRef(() => PanelItem), {descendants: true}) items;
See also angular 2 / typescript : get hold of an element in the template
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With