Home > OS >  Getting the height of an @ContentChild?
Getting the height of an @ContentChild?

Time:11-17

In this demo the CardHeaderComponent from the following layout is retrieved with an @ContentChildren decorator:

  <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 this is the decorator that gets the CardComponentHeader:

  @ContentChildren(CardHeaderComponent) headers: QueryList<ElementRef>;

And we can log it like this:

  ngAfterViewInit() {
    console.log(this.headers.first); //CardHeaderComponent{__ngContext__: 73}
    console.log(this.headers.first.nativeElement); //undefined
  }

I'd like the get the height of the header, however when I try to access the nativeElement it's undefined.

Thoughts?

CodePudding user response:

You are using the actual component as an input to the contentChild so you will get the component reference (component object instead of dom element), you can instead, specifically tell to fetch the elementRef which contains height, the below line needs to be changed!

import {
  AfterViewInit,
  Component,
  ContentChildren,
  ElementRef,
  Input,
  QueryList,
  ViewChild,
} from '@angular/core';
import { CardHeaderComponent } from './card-header.component';

@Component({
  selector: 'card',
  template: `
  <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>
  `,
  styles: [`:host { display:flex; flex-direction:column;}`],
})
export class CardComponent implements AfterViewInit {
  @ContentChildren(CardHeaderComponent, { read: ElementRef }) //      <---- changed here
  headers: QueryList<ElementRef>; 

  ngAfterViewInit() {
    console.log(this.headers.first);
    console.log(this.headers.first.nativeElement);
    console.log(this.headers.first.nativeElement.offsetHeight);
  }
}

forked stackblitz

  • Related