@ContentChildren returns empty list, if content passed through 2 components

2.8k Views Asked by At

I have next structure:

Child component template (it's the simplest):

   <div>Child</div>
  

Parent component template:

  <div><h1>Parent</h1>
    <middle>
        <ng-content></ng-content>
    </middle>
  </div>

And as you can see we have one more in the middle, Middle Component templtate:

  <div>
    <h1>Middle</h1>
    <ng-content></ng-content>
  </div> 

And I am using next way:

  <parent>
      <child>hi</child>
      <child>there</child>
  </parent>

Problem: I couldn't get ContentChildren of Child components in Middle component?

Should angular2 support it? If not, then why?

Plnkr Demo - see output in console

2

There are 2 best solutions below

4
Günter Zöchbauer On

There are no content-children in Middle, they are passed right through to the outermost <ng-content>.

If you pass a Child in Parent as child of Middle, you get a contentchild in middle.

Plunker example

You could use selectors in <ng-content select="..."> to specify which elements should be projected to which <ng-content>

0
Khaled Lela On

descendants - True to include all descendants, otherwise include only direct children.

@Component({
    selector: 'parent',
    directives: [ Middle],
    template: `<div><h1>Parent</h1>
        <middle>
            <ng-content></ng-content>
        </middle>
      </div>`
})
export class Parent {
    @ContentChildren(Child, { descendants: true }) children: QueryList<Child>;
    ngAfterContentInit() {
        console.log(this.children.length);
    }
}