【问题标题】:@ContentChildren is not being populated when parent render items using ng-content当使用 ng-content 的父渲染项目时,@ContentChildren 没有被填充
【发布时间】:2018-01-19 05:39:31
【问题描述】:

我有三个组件: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 {}

小组组:

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

面板项目:

@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” - 在这种情况下,永远不会渲染孩子,这有点奇怪。

我错过了什么吗?

这里是plunk:

【问题讨论】:

标签: angular


【解决方案1】:

使用descendants: true

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

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

【讨论】:

  • 这救了我的培根
  • 我已经尝试修改现有的演示,但它不起作用。你能再检查一下吗?
  • @javaLearner 你能在stackblitz.com创建一个复制吗?
  • 如您所见,items.length 仍为 0。不知道是不是漏掉了什么?
  • 你为什么使用这么旧的 Angular 版本? stackblitz.com 会让这更容易。只需单击 Angular 即可获得一个完整设置的项目。
【解决方案2】:

我遇到了类似的问题,但似乎也可以通过从面板项中删除选择选项来解决这个问题。我假设因为 select='panel-item' 只在寻找内容,但有一个嵌套对象作为内容。如果您删除限制(在 plunk 示例中),它会显示它。

【讨论】:

    猜你喜欢
    • 2017-09-21
    • 2016-04-06
    • 1970-01-01
    • 2020-12-28
    • 2021-03-11
    • 1970-01-01
    • 2020-11-03
    • 2018-06-17
    • 2018-01-25
    相关资源
    最近更新 更多