javascript - Angular2 @ContentChildren 未填充在父 <ng-content> 中

标签 javascript angular angular2-components angular2-ngcontent

问题:

@ContentChildren 似乎不适用于 Parent <ng-content>容器。 即使内容是组件的子项。

笨蛋: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 的长度component 子组件为 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() { }

}

enter image description here

最佳答案

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

引用这个plunker我从你那里 fork 了。

关于javascript - Angular2 @ContentChildren 未填充在父 <ng-content> 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43600969/

相关文章:

javascript - Protractor 获取模型值

javascript - 路由参数在守卫中不可用

angular - 如何使用 ResolveComponentFactory() 但使用字符串作为键

javascript - 你能在 React 渲染 Prop 的模板字符串中使用 jsx 吗?

javascript - 获取上层li文本

javascript - 在 Javascript 中查找 (x,y) 坐标处的元素(最高可见元素)

javascript - 如何从 Angular 2 组件访问外部 javascript 文件

angular2 *ng用于在 ul>li 上设置样式并传递颜色值

angular - 动态更改 Angular 4 组件的模板

angular - 将变量传递给自定义组件