简体   繁体   English

Angular2 @ContentChildren未填充父级内部<ng-content>

[英]Angular2 @ContentChildren not populated inside parent <ng-content>

ISSUE: 问题:

@ContentChildren does not seem to work on Parent <ng-content> containers. @ContentChildren似乎不适用于父<ng-content>容器。 Even if the content is a child of the component. 即使内容是组件的子级。

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

NOTE : I Am using {descendants: true} 注意 :我正在使用{descendants: true}

Example Code: 示例代码:

Main HTML: 主要HTML:

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

Child Component: 子组件:

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

Parent Component: 父组件:

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

Problem The length of the test component is 0 for the child component, but 3 for the parent component. 问题子组件的test组件长度为0,而父组件的长度为3。


Detailed Code: 详细代码:

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() { }

}

在此输入图像描述

ContentChildren will count only directives assigned to the current Component . ContentChildren仅计算分配给current Component指令。 For your situation, while assigning test directive to ChildComponent , you should count directives at ChildComponent itself. 根据您的情况,在为ChildComponent分配test指令时,您应该在ChildComponent本身计算指令。

refer this plunker I forked from you. 请参考我从你那里分叉的这个龙头

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM