【问题标题】:Is it possible to use @ContentChild and @ContentChildren for projected DOM elements?是否可以将 @ContentChild 和 @ContentChildren 用于投影的 DOM 元素?
【发布时间】:2019-12-11 17:22:08
【问题描述】:

假设内容投影:

  <app-page>
    <h1>Hello</h1>
  </app-page>

我可以通过@ContentChild 改变 app-page 组件中的 h1 吗?

到目前为止(在应用程序页面中的 &lt;ng-content&gt; 之后),我已经在 ngAfterContentInit() 中检查了 @ContentChild('h1', {static: true}) header;。是undefined。

另一方面,如果投影内容是一个组件,@ContentChild(DummyComponent) content;,它会被正确初始化。

我还阅读了文档:

不检索其他组件模板中的元素或指令,因为组件的模板对于其祖先来说始终是一个黑盒子。

我的问题是,组件能否以任何方式改变投影内容中的原生元素?

【问题讨论】:

  • 它显示undefined,因为h1既不是组件、指令或模板引用。如果您执行&lt;h1 #header&gt;...&lt;/h1&gt; 和@ContentChild(header, ...),它应该可以工作。

标签: angular


【解决方案1】:

您无法访问尚未分配模板引用变量的元素 bcoz

app.component.ts

<app-page>
    <h1 #ref>Hello</h1>
 </app-page>

app.page.component.ts

@ContentChild("h1") header: ElementRef;

Example

【讨论】:

    猜你喜欢
    • 2011-11-05
    • 1970-01-01
    • 2018-07-09
    • 2019-06-09
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 2013-06-26
    • 1970-01-01
    相关资源
    最近更新 更多