angularng-content

Is there any way to do something, in order to ContentChildren could find components that are inside parent's <ng-content></ng-content>?


I have some components from third-party library, that work fine, when use next way:

<lib>
  <lib-inner [text]="'111'"></lib-inner>
  <lib-inner [text]="'222'"></lib-inner>
</lib>

Simplified imitation of 'lib' and 'lib-inner' components code:

@Component({
  selector: "lib",
  template: `
    <ng-container *ngFor="let c of allInner;">
      <button>{{ c.text }}</button>
    </ng-container>
  `
})
export class LibComponent {
  @ContentChildren(LibInnerComponent) allInner: QueryList<LibInnerComponent>;
}
@Component({
  selector: "lib-inner",
  template: ``
})
export class LibInnerComponent {
  @Input() text: string;
}

I want to create wrapper component:

<wrapper-for-lib>
  <lib-inner [text]="'aaa'"></lib-inner>
  <lib-inner [text]="'bbb'"></lib-inner>
</wrapper-for-lib>
@Component({
  selector: "wrapper-for-lib",
  template: `
    <lib>
      <ng-content></ng-content>
      <lib-inner [text]="'default'"></lib-inner>
    </lib>
  `
})
export class WrapperForLibComponent {}

When we use this 'wrapper-for-lib' component, we see only 'default' button, but don't see buttons 'aaa' and 'bbb'.

'lib' component's ContentChildren() don't find 'lib-inner' components that are in ng-content,

Is there any way to solve this?

Notice, I can't change code of 'lib' and 'lib-inner', because they imitate case for real third-party library components, which I can't change.

workable example with above code

example for same case and real library component


Solution

  • You can select all the lib-inner components from your wrapper and loop them in your template.

    Component({
        selector: "wrapper-for-lib",
        template: `
        <lib>
            <ng-content></ng-content>
            <ng-container *ngFor="let inner of libInners">
                <lib-inner [text]="inner.text"></lib-inner>
            </ng-container>
        </lib>
    `
    })
    export class WrapperForLibComponent {
        @ContentChildren(LibInnerComponent) libInners: QueryList<LibInnerComponent>;
      }