【问题标题】:Angular2 @ContentChildren not populated inside parent <ng-content>Angular2 @ContentChildren 未填充在父 <ng-content> 中
【发布时间】:2017-09-21 21:29:10
【问题描述】:

问题:

@ContentChildren 似乎不适用于父 &lt;ng-content&gt; 容器。 即使内容是组件的子组件。

Plunker:https://plnkr.co/edit/J5itJmDfwKwtBsG6IveP?p=preview

注意:我使用的是{descendants: true}

示例代码:

主 HTML:

<div>
  <child>
    <test></test>
    <test></test>
    <test></test>
  </child>
  <br><br>
  <parent>
    <test></test>
    <test></test>
    <test></test>
  </parent>
</div>

子组件:

<h2>Child</h2>
<parent>
  <ng-content></ng-content>
</parent>

父组件:

<h3>Parent</h3>
<ng-content></ng-content>
<div class='length'>Line count : {{length}}</div>

问题 test组件的长度对于子组件是0,对于父组件是3。


详细代码:

import {
  Component, ContentChildren, Directive
} from '@angular/core';


@Directive({selector: 'test'})
export class Test {}

@Component({
  selector: 'parent',
  template: `
    <h3>Parent</h3>
    <ng-content></ng-content>
    <div class='length'>Line count : {{length}}</div>
  `
})
export class ParentComponent  {

  @ContentChildren(Test, {descendants: true}) private tests : QueryList<Test>;

  constructor() { }

  get length () {
    return this.tests.length;
  }
}

import {
  Component
} from '@angular/core';


@Component({
  selector: 'child',
  template: `
  <h2>Child</h2>
  <parent>
    <ng-content></ng-content>
  </parent>
  `
})
export class ChildComponent  {

  constructor() { }

}

【问题讨论】:

  • 为什么要颠倒父子?孩子应该在父母内部,反之亦然。无论如何,这是我遇到的确切问题。并且文档没有说它不应该工作。 angular.io/api/core/ContentChildren :/

标签: javascript angular angular2-components angular2-ngcontent


【解决方案1】:

ContentChildren 将只计算分配给current Component 的指令。对于您的情况,在将 test 指令分配给 ChildComponent 时,您应该计算 ChildComponent 本身的指令。

请参考这个plunker我从你那里分叉出来的。

【讨论】:

  • 这个解决方案效果很好。我觉得 Angular 应该能够完成上述功能 :(
  • @KevinUpton 哦,我以前也有这种感觉。但经过一番研究,我仍然没有发现任何东西。
猜你喜欢
  • 1970-01-01
  • 2021-03-11
  • 2020-11-03
  • 2016-10-29
  • 2018-06-17
  • 2016-04-06
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
相关资源
最近更新 更多