一句话描述5个关键词的作用:
ng-template是备胎(模板):通常在html里面作为备用模板,当绑定了对应的#标记的时候才会显示
ng-container是舔狗(虚拟标签):包裹的内容显示,而自身标签不会出现在html中
ng-content是替身(替代组件包裹内容、插槽):通常出现在子组件中,用于替代父组件中><尖括号包裹的内容,并在子组件对应的ng-content位置渲染
ngTemplateOutlet是渣女的闺蜜(指向绑定的模板):让舔狗去做备胎就做备胎,做什么样的备胎就绑定对应的ng-template引用#标记
ngProjectAs是伪装兽:把标签匿名成其他名称被ng-content的select获取
接下来就用一个综合的例子讲解这5者分别的用处
[ngTemplateOutlet]等同于*ngTemplateOutlet,以下几种写法是等效的:
<ng-container [ngTemplateOutlet]="myTemplate" ></ng-container>
<ng-container *ngTemplateOutlet="myTemplate"></ng-container>
<div [ngTemplateOutlet]="myTemplate" ></div><!--这里的div可以换成任意标签-->
<div *ngTemplateOutlet="myTemplate"></div><!--这里的div可以换成任意标签-->
ng-content就是把父组件中,插入子组件俩尖括号夹住的html内容部分替代作为一个占位符使用,这里ng-content还有一个select属性可以分节点替代类似vue插槽的功能
父组件app.component.html代码
<app-home>
<ng-container [ngTemplateOutlet]="myTemplate" ></ng-container>
<hr>
<ng-container *ngTemplateOutlet="myTemplate"></ng-container>
<h1>这是个大标题</h1>
<hr>
<h2 class="small-title">这是个小标题</h2>
<hr>
<h3 ngProjectAs="sub-title">这是个副标题</h3>
</app-home>
<!-- 模板---------------------------------------- -->
<ng-template #myTemplate>
<b>这里是模板文字</b>
</ng-template>
子组件app-home.component.html代码
<ng-content select='sub-title'></ng-content>
<hr>
<ng-content select='.small-title'></ng-content>
<hr>
<ng-content select='h1'></ng-content>
<br>
<ng-content></ng-content>
最终渲染出来html如下
看下图的对比关系,就明白了这几个ng标签(属性) 有啥作用了