1

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?

Ole
  • 41,793
  • 59
  • 191
  • 359

1 Answers1

2

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>
Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134
  • Hi Matthieu - Thanks that works! Do you know if that's the only way. I was under the impression (Based on various tutorials) that the projected element could be selected just by using the name of the element as the selector ...? – Ole Aug 04 '23 at 00:56
  • 1
    @Ole the angular documentation actually makes conflicting statements about this. In one section it says you can pass any valid Dom selector and even links to mdn. Elsewhere, it confirms what this answer indicates – Aluan Haddad Aug 04 '23 at 02:32
  • 1
    You can use as selector the **name of the class**, if your "header" it's a component that its class "HeaderComponent" you need use "HeaderComponent". – Eliseo Aug 04 '23 at 07:06
  • @Eliseo - Oh OK - Cool thanks!! – Ole Aug 04 '23 at 16:17
  • 1
    Created a Github issue to get the documentation fixed ... https://github.com/angular/angular/issues/51272 – Ole Aug 04 '23 at 16:21
  • It's interesting to see that there is a proposal to rename the variable `selector` of the query to be less confusing. Would that be enough to you ? – Matthieu Riegler Aug 04 '23 at 22:28