如何将模板内定义的内容投影到ngComponentOutlet?
如何将模板内定义的内容投影到ngComponentOutlet加载的组件中?
你尝试的代码无法生效,是因为*ngComponentOutlet不支持直接在标签内部嵌套内容进行投影,必须通过它的content输入属性传递模板片段。具体实现步骤如下:
解决方案:使用ng-template+ViewChild传递投影内容
- 用
<ng-template>包裹你需要投影的内容,并添加模板引用标识 - 通过
@ViewChild获取该模板的引用实例 - 在
*ngComponentOutlet中绑定content属性,传入包含模板引用的数组
完整代码示例:
import { Component, ViewChild, TemplateRef } from '@angular/core'; import { CommonModule } from '@angular/common'; @Component({ template: `<ng-content></ng-content>`, }) export class MyComp {} @Component({ selector: 'my-app', standalone: true, imports: [CommonModule], template: ` <ng-template #projectionContent> <div #ref>我的投影内容</div> </ng-template> <div *ngComponentOutlet="cmp; content: [projectionContent]"></div> `, }) export class App { cmp = MyComp; @ViewChild('projectionContent') projectionContent!: TemplateRef<any>; }
多插槽投影扩展(可选)
如果目标组件包含带选择器的多插槽<ng-content>,可以定义多个<ng-template>并按顺序传入content数组:
// 带多插槽的目标组件 @Component({ template: ` <ng-content></ng-content> <ng-content select="[slot=footer]"></ng-content> `, }) export class MyComp {} // 父组件实现多插槽投影 @Component({ selector: 'my-app', standalone: true, imports: [CommonModule], template: ` <ng-template #defaultSlot> <div>默认插槽内容</div> </ng-template> <ng-template #footerSlot> <div slot="footer">页脚插槽内容</div> </ng-template> <div *ngComponentOutlet="cmp; content: [defaultSlot, footerSlot]"></div> `, }) export class App { cmp = MyComp; @ViewChild('defaultSlot') defaultSlot!: TemplateRef<any>; @ViewChild('footerSlot') footerSlot!: TemplateRef<any>; }
内容的提问来源于stack exchange,提问作者Matthieu Riegler
相关产品推荐
相关产品推荐

