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

Angular循环内子组件仅显示最后一个注入内容的问题咨询

Angular内容投影问题:内容仅显示在最后一个子组件的解决方案

问题原因

当前代码中,父组件通过*ngFor循环渲染3个子组件,每个子组件都尝试用<ng-content>接收来自App组件的投影内容。但Angular的内容投影机制默认只能将内容渲染一次,所以最后一个子组件会获取到唯一的投影内容,前面的子组件无法显示该内容。

解决方案:使用模板引用与ngTemplateOutlet

通过将投影内容包装为模板(ng-template),再将模板传递给每个子组件,让子组件独立实例化模板,即可实现每个子组件都显示注入内容。

修改后的完整代码

import 'zone.js/dist/zone';
import { Component, ContentChild, Input, TemplateRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { bootstrapApplication } from '@angular/platform-browser';

@Component({
  selector: 'child',
  template: `child<br />
  <ng-container *ngTemplateOutlet="contentTemplate"></ng-container>
  <hr />`,
  standalone: true,
  imports: [CommonModule],
})
export class ChildComponent {
  @Input() contentTemplate!: TemplateRef<any>;
}

@Component({
  selector: 'parent',
  template: `
    <child *ngFor="let item of [1,2,3]" [contentTemplate]="slotTemplate"></child>
`,
  standalone: true,
  imports: [CommonModule, ChildComponent],
})
export class ParentComponent {
  @ContentChild('slot') slotTemplate!: TemplateRef<any>;
}

@Component({
  selector: 'my-app',
  standalone: true,
  imports: [CommonModule, ParentComponent],
  template: `
    <parent>
      <ng-template #slot>injected content</ng-template>
    </parent>`,
})
export class App {
  name = 'Angular';
}

bootstrapApplication(App);

关键调整说明

  1. App组件:将原<ng-container slot>替换为<ng-template #slot>,把内容包装成可复用的模板,并添加模板引用#slot。
  2. Parent组件:通过@ContentChild('slot')获取App组件传递的模板实例,再通过输入属性[contentTemplate]将模板传递给每个循环渲染的子组件。
  3. Child组件:接收父组件传入的模板,使用*ngTemplateOutlet指令实例化模板,实现内容的重复渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 23:02:54