@ContentChildren returns empty list, if content pa

2019-07-23 03:24发布

问题:

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

回答1:

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>