Search code examples
javascriptangulartypescriptangular-content-projection

Getting a projected header element using @ContentChild?


Within this component demo I'm trying to grab the projected header element like this:

@ContentChild('header') header!: HTMLElement;

The demo tries to log the element within the ngAfterContentInit() method like this:

  ngAfterContentInit() {
    console.log(this.header);
  }

Not getting any love, even though the header projects fine within within the main.ts demo component.

  <my-test>
  <header>header</header>
  Test
  </my-test>

Any ideas?


Solution

  • The selector of a query needs to be a class of a template variable.

    In your case to fix the issue, you'll need to add a template variable #header to your header.

    <header #header>header</header>