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

Angular父子组件ng-content使用问题:子组件内容不显示求助

问题解决:Angular父子组件内容投影不显示的问题

问题原因

带有child属性的<span>是<app-parent>的直接内容,但<app-child>的<ng-content>只能接收自身直接父组件传递的内容,当前<span child>并没有传递到<app-child>内部,所以无法显示。

解决方案

修改<app-parent>的模板,将接收到的child内容显式传递给内部的<app-child>组件:

修正后的app-parent模板

parent component
<ng-content select="[parent]"></ng-content>
<app-child>
  <!-- 将父组件接收到的child内容投影给子组件 -->
  <ng-content select="[child]" ngProjectAs="[child]"></ng-content>
</app-child>

app-child模板保持不变

child component
<ng-content select="[child]"></ng-content>

app-root模板无需修改

<app-root>
   <app-parent>
      <span parent>this should appear in parent </span>
      <span child> this should appear in child </span>
   </app-parent>
</app-root>

原理说明

  • <app-parent>通过<ng-content select="[child]">先接收来自根组件的<span child>内容。
  • ngProjectAs="[child]"用来告诉Angular:把这段内容当作匹配<app-child>中select="[child]"的投影内容,从而让<app-child>的<ng-content>能正确捕获并显示这段内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 21:52:46