Home > Net >  Getting ng-content components using @ViewChild?
Getting ng-content components using @ViewChild?

Time:11-17

I've created a card with a template that uses ng-content slots like this:

  <ng-content select="card-header"></ng-content>
  <ng-content select="card-body"></ng-content>
  <ng-content></ng-content>
  <ng-content select="card-footer"></ng-content>

And within the CardComponent I'm trying to grab the CardHeaderComponent reference using @ViewChild like this:

  @ViewChild(CardHeaderComponent)
  header: CardHeaderComponent;

I does not look like it is succeeding though, per the log statement in ngAfterViewInit:

    console.log(this.header);

This is the Stackblitz demo.

Thoughts?

CodePudding user response:

Instead of using @ViewChild use @ContentChildren like this:

@ContentChildren(CardHeaderComponent) header: QueryList<ElementRef>;
  • Related