'How to allow the children component to use a wrapper when the parent component uses @ContentChildren query

The actual problem is more complicated, but here is the simplified version.

I have a parent component called app-grid, and child component called app-grid-row. app-grid-row has a templateRef which contains the columns.

In app-grid, I need to use @ContentChildren to query all the app-grid-row content projection. I can't use <ng-content> because I need to modify the way they are rendered.

app-grid.component.ts:

export class GridComponent {
  
  @ContentChildren(GridRowComponent)
  public rows: QueryList<GridRowComponent>;

  ........

}

app-grid.component.html:

// Again, this is a simplified version

<div class="row" *ngFor="let row of rows">
  <ng-container *ngTemplateOutlet="row.templateRef></ng-container>
</div>

This works fine:

<app-grid>
  <app-grid-row>...</app-grid-row>
  <app-grid-row>...</app-grid-row>
</app-grid>

What I want to do is to have a wrapper component that wraps all the app-grid-row because they can get really long.

With a wrapper component, this doesn't work:

<app-grid>
  <app-wrapper></app-wrapper>
</app-grid>

Where app-wrapper.component.html contains all the app-grid-row.

This is the link to the demo: stackblitz



Solution 1:[1]

I think this can't be done as is, when we check the description of the ContentChildren annotation, it says :

Does not retrieve elements or directives that are in other components' templates, since a component's template is always a black box to its ancestors.

https://angular.io/api/core/ContentChildren#description

So I guess you should add some kind of binding or logic in your wrapper ?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alain Boudard