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

Angular中*ngTemplateOutlet与[ngTemplateOutlet]的区别是什么

Angular中*ngTemplateOutlet与[ngTemplateOutlet]的区别

二者核心功能完全一致,本质是Angular结构型指令的两种写法差异:

  • *ngTemplateOutlet是官方推荐的微语法糖写法,代码更简洁易读,Angular编译阶段会自动对该写法做转换,无需手动处理模板容器的包裹逻辑。常见使用示例如下:
    <ng-container *ngTemplateOutlet="customTpl; context: { $implicit: '默认值', name: '测试' }"></ng-container>
    
  • [ngTemplateOutlet]是语法糖展开后的原生属性绑定写法,需要手动写在<ng-template>标签上,上下文也需要单独用[ngTemplateOutletContext]绑定,完整等价写法如下:
    <ng-template 
      [ngTemplateOutlet]="customTpl"
      [ngTemplateOutletContext]="{ $implicit: '默认值', name: '测试' }"
    ></ng-template>
    

两种写法最终编译后的运行产物完全相同,所以实际使用时都可以正常生效。官方更推荐使用带*的微语法写法,能减少冗余代码,降低手动编写<ng-template>相关绑定的出错概率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 15:57:02