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

Angular中获取含ng-template元素的innerHTML时,如何显示模板内容?

解决方案

首先明确:<ng-template> 是Angular的惰性模板容器,它本身不会被直接渲染到DOM中,只会被编译为一个注释节点(也就是你看到的 <!--container-->)。要让模板内的内容显示在DOM里,需要主动触发它的渲染。

方法1:使用 ngTemplateOutlet 直接渲染模板

修改你的 app.component.html:

<div #content>
    Hello world
    <ng-template #myTemplate>
        inside template
    </ng-template>
    <!-- 使用 ngTemplateOutlet 渲染模板内容 -->
    <ng-container *ngTemplateOutlet="myTemplate"></ng-container>
</div>

这样修改后,模板内的内容会被直接渲染到<div #content>内部,控制台输出就会符合你的预期。

方法2:如果不需要复用模板,直接替换为 <ng-container>

如果这个模板不需要在其他地方复用,完全可以把<ng-template>换成<ng-container>,它是一个不会产生额外DOM节点的逻辑容器,内容会直接渲染:

<div #content>
    Hello world
    <ng-container>
        inside template
    </ng-container>
</div>

验证结果

修改后,执行console.log(this.refContent.nativeElement);,控制台输出将变为:

<div _ngcontent-kst-c255=""> 
    Hello world 
    inside template
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 09:27:23