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

使用NgComponentOutlet实现Angular组件动态内容投影渲染

解决通过NgComponentOutlet传递ngTemplate实现动态内容投影的问题

问题分析

你当前代码的核心问题在于*ngComponentOutlet的语法错误(item .component多了空格)以及content属性的使用方式不正确,导致无法将模板传递给动态加载的组件完成内容投影。

修正方案

1. 修正主组件模板代码

需要修正*ngComponentOutlet的语法,正确绑定模板到content属性,同时通过context给模板传递数据:

<mat-button-toggle-group appearance="legacy" [(ngModel)]="selectedClockType">
    <mat-button-toggle *ngFor="let item of items" [value]="item" color="primary">
        {{ item.label }}
    </mat-button-toggle>  
</mat-button-toggle-group>

@for (item of items; track item.id) {   
    <!-- 修正语法错误,绑定content和上下文 -->
    <ng-container *ngComponentOutlet="item.component; content: [actionItesm]; context: { data: item.contentData }"></ng-container> 
}

<ng-template #actionItesm let-data="data">{{data}}</ng-template>

2. 确保组件类中items的结构正确

主组件类中需要定义包含动态组件、标签、ID和投影数据的数组:

import { ComponentA } from './component-a.component';
import { ComponentB } from './component-b.component';

// ...

items = [
    {
        id: 1,
        label: '组件A',
        component: ComponentA,
        contentData: '这是传递给组件A的投影内容'
    },
    {
        id: 2,
        label: '组件B',
        component: ComponentB,
        contentData: '这是传递给组件B的投影内容'
    }
];
selectedClockType: any;

3. 动态组件保持原结构

你的component-a.html和component-b.html中的<ng-content></ng-content>无需修改,它们会自动接收*ngComponentOutlet传递的模板内容。

关键说明

  • content属性接受TemplateRef数组,因此需要用[actionItesm]将模板包装为数组传递
  • context参数用于给模板传递上下文数据,对应模板中let-data="data"的变量绑定
  • 注意item.component的写法,不要加空格,确保正确引用动态组件类

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 17:36:11