使用@ContentChild获取投影的标题元素?

huangapple go评论66阅读模式
英文:

Getting a projected header element using @ContentChild?

问题

此组件演示中,我试图像这样获取投影的 header 元素:

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

该演示尝试在 ngAfterContentInit() 方法中记录该元素,如下所示:

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

尽管 main.ts 演示组件中的头部投影正常,但我没有得到任何输出。

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

有任何想法吗?

英文:

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

@ContentChild(&#39;header&#39;) 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.

  &lt;my-test&gt;
  &lt;header&gt;header&lt;/header&gt;
  Test
  &lt;/my-test&gt;

Any ideas?

答案1

得分: 2

查询的选择器需要是模板变量的类。

在你的情况下,要解决这个问题,你需要在你的头部添加一个模板变量 #header

<header #header>header</header>
英文:

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.

&lt;header #header&gt;header&lt;/header&gt;

huangapple
  • 本文由 发表于 2023年8月4日 03:39:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76831170.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定