Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 519
Kevin Upton Avatar asked Oct 30 '22 08:10

Kevin Upton


1 Answers

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.

like image 72
Pengyy Avatar answered Nov 04 '22 22:11

Pengyy