Angular中ng-template、ng-container、ng-content 的用法
1、ng-container
此标签不渲染成DOM;默认显示标签内部内容,也可以使用结构型指令(ngIf、ngFor…)
代码块:
<ng-container>
<p>Hello World !!!</p>
</ng-container>
网页渲染结果:
<p _ngcontent-vkg-c0="">Hello World !!!</p>
2、ng-template
模板元素,默认情况内部元素不可见。使用方法:
方法一:使用 ngIf 属性,值为 true 显示内容
<ng-template *ngIf="condition">
<p>Hello World !!!</p>
</ng-template>
还有多种使用方法在此不一一列举,详细介绍可以查看官网
3、ng-content
父组件调用子组件时,将父组件内容投射到子组件指定位置(子组件中 ng-content 所在位置);类似 VUE 中的插槽。分为默认投射,具名投射。
3.1、默认投射 - 子组件中只有一个 ng-content 时
父组件中引入子组件:
<app-child-com>
<p>- parent component content !!! -</p>
</app-child-com>
子组件:
<p>child component content - begin</p>
<ng-content></ng-content>
<p>child component content - end</p>
显示效果:
child component content - begin
- parent component content !!! -
child component content - end
父组件中 p标签的位置投射到子组件中ng-content的所在位置。
3.1、具名投射 - 子组件有多个 ng-content,需要指定名字进行指定位置投射
父组件内容
<app-child-com>
<header>
header - parent component content !!! -
</header>
<div id="demo">
id selector - parent component content !!! -
</div>
<div name="demo">
name - parent component content !!! -
</div>
</app-child-com>
子组件内容
<p>child component content</p>
<ng-content select="header"></ng-content>
<p>child component content</p>
<ng-content select="#demo"></ng-content>
<p>child component content</p>
<ng-content select="[name=demo]"></ng-content>
使用 select 属性,支持 CSS 选择器,投射对应位置