You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中使用ng-content时内容不显示的原因咨询

问题原因及解决办法

核心原因

Angular 初始化根组件时,会完全替换index.html中<app-root>标签内部的所有原始内容,而不是将其作为内容投影的来源。你写在<app-root>里的<h1>Hello this is from app-root</h1>会被Angular的启动逻辑直接清除,所以app.component.html里的<ng-content>找不到任何内容可以投影。

正确的内容投影用法

如果需要使用内容投影,应该在子组件中用<ng-content>,然后在根组件的模板(app.component.html)里引用该子组件并传入投影内容。举个例子:

  1. 创建一个子组件(比如app-child),其模板app-child.component.html写:
<ng-content></ng-content>
  1. 在app.component.html中使用这个子组件并传入内容:
<app-child>
  <h1>Hello this is from app-root</h1>
</app-child>

这样就能正常显示投影内容了。


内容的提问来源于stack exchange,提问作者dev sathwik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 12:45:37