5

ISSUE:

@ContentChildren does not seem to work on Parent <ng-content> containers. Even if the content is a child of the component.

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

NOTE: I Am using {descendants: true}

Example Code:

Main 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.


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

}

enter image description here

4

1 回答 1

2

ContentChildren will count only directives assigned to the current Component. For your situation, while assigning test directive to ChildComponent, you should count directives at ChildComponent itself.

refer this plunker I forked from you.

于 2017-04-25T03:45:42.227 回答