angular – 使用ng-content在父项呈现项目时未填充@ContentChildren

前端之家收集整理的这篇文章主要介绍了angular – 使用ng-content在父项呈现项目时未填充@ContentChildren前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有三个组件:Panel,PanelGroup(ul)和PanelItem(li):

面板:

@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';
}

如上例所示,我尝试在PanelGroup组件中获取内容子项,但集合始终为空.还尝试将选择器添加到其中的“ng-content” – 在这种情况下,子节点永远不会被渲染,这有点奇怪.

我错过了什么吗?

这是插件

> demo

解决方法

使用后代:true:

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

另见angular 2 / typescript : get hold of an element in the template

猜你在找的Angularjs相关文章