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

Angular中如何在组件指定位置调用另一组件以复用内容?

实现Angular组件内容复用的解决方案

嘿,你这个需求刚好可以用Angular的**内容投影(Content Projection)**来解决,完全不用复制粘贴代码就能实现组件内容的复用,具体操作很简单:

步骤1:修改mycomponent2.component.html的模板

在你想要插入父组件内容的位置,替换掉注释,用Angular的<ng-content>标签——这个标签就是专门用来接收外部传入的内容的:

<div class="bg-blue">
  <ng-content></ng-content>
</div>

步骤2:保持mycomponent.component.html的写法不变

你原来的写法已经是正确的内容传递方式了:

<app-mycomponent2>
  <p> this is a text </p>
</app-mycomponent2>

原理说明

当Angular渲染的时候,<app-mycomponent2>标签包裹的所有内容(也就是这里的<p> this is a text </p>),都会被自动“投影”到mycomponent2模板里<ng-content>所在的位置,最终渲染出来的结构就是:

<div class="bg-blue">
  <p> this is a text </p>
</div>

这样你就实现了内容的复用,以后如果需要在mycomponent2里展示不同的内容,只需要在使用<app-mycomponent2>的时候包裹对应的内容就行,完全不用修改mycomponent2的代码。

如果以后你需要更复杂的多区域投影,还可以给<ng-content>加上select属性来指定匹配规则,比如:

<!-- mycomponent2.component.html -->
<div class="bg-blue">
  <ng-content select="[header]"></ng-content>
  <ng-content select="[body]"></ng-content>
</div>

<!-- 使用时 -->
<app-mycomponent2>
  <h2 header>这是标题</h2>
  <p body>这是正文内容</p>
</app-mycomponent2>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:35:21