Angular中ng-template、ng-container、ng-content 的用法

本文详细介绍了Angular中的ng-template、ng-container和ng-content的用法,包括ng-container的隐藏特性、ng-template的条件展示、ng-content的父子组件内容投射及其具名投射实例。

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 选择器,投射对应位置

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值