【问题标题】:@ContentChildren returns empty list, if content passed through 2 components@ContentChildren 返回空列表,如果内容通过 2 个组件
【发布时间】:2017-07-31 05:00:43
【问题描述】:

我有下一个结构:

子组件模板(最简单的):

   <div>Child</div>
  

父组件模板:

  <div><h1>Parent</h1>
    <middle>
        <ng-content></ng-content>
    </middle>
  </div>

正如你所见,我们中间还有一个, 中间组件模板:

  <div>
    <h1>Middle</h1>
    <ng-content></ng-content>
  </div> 

我正在使用下一种方式:

  <parent>
      <child>hi</child>
      <child>there</child>
  </parent>

问题:我无法在 Middle 组件中获取 Child 组件的 ContentChildren?

angular2 应该支持它吗?如果不是,那为什么?

Plnkr Demo - 在控制台中查看输出

【问题讨论】:

  • 你的问题不清楚
  • 我已经准备好澄清了,只是问问题。您还可以查看演示,打开控制台并检查它:对于父组件 - 我在 QueryList 中得到 2 个元素,但对于中间 - 0,我是否希望看到相同的 2 个组件
  • 那么每个的计数应该是多少??
  • 我预计在这两种情况下都会看到 2 个子组件,因为它们是相同的
  • 你为什么用这种方式?

标签: angular angular2-decorators


【解决方案1】:

descendants - 真包括所有后代,否则只包括 直系子女。

@Component({
    selector: 'parent',
    directives: [ Middle],
    template: `<div><h1>Parent</h1>
        <middle>
            <ng-content></ng-content>
        </middle>
      </div>`
})
export class Parent {
    @ContentChildren(Child, { descendants: true }) children: QueryList<Child>;
    ngAfterContentInit() {
        console.log(this.children.length);
    }
}

【讨论】:

    【解决方案2】:

    Middle 中没有 content-children,它们直接传递到最外层的&lt;ng-content&gt;

    如果你在Parent 中传递一个Child 作为Middle 的孩子,你会在中间得到一个contentchild。

    Plunker example

    您可以在&lt;ng-content select="..."&gt; 中使用选择器来指定应将哪些元素投影到哪个&lt;ng-content&gt;

    【讨论】:

    • 但是它看起来对你来说是一种正确的行为吗?文档中有关于它的任何信息吗?
    • 是的。 ng-content 只是传递。最后抓住了。我不知道这方面的具体文档,仅来自 GitHub 问题中的讨论。
    • 你能给我一些 Github 问题的链接,我可以在哪里阅读更多相关信息?
    • 抱歉,不记得在哪里提到过。我关注了 1.5 年。
    猜你喜欢
    • 2016-11-02
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 2013-04-13
    • 1970-01-01
    • 2019-10-10
    • 1970-01-01
    相关资源
    最近更新 更多