ng中的ng-content ng-template ng-container

在angular中,有这样三个自带的标签,但是在angular的文档中没有说明,只有在api中有简单的描述,摸索了半天才搞懂是咋回事。

ng-content

复制代码
<div>
  <ng-content select=".header">

  </ng-content>
  <hr/>
  <ng-content select=".footer">

  </ng-content>
</div>
复制代码

ng-content有一个select的属性,可以选择对应的嵌入标签的属性,.header的意思就是选中class=header的标签填充到当前的位置

<app-contentdemo>
  <div class="header">
    header
  </div>
  <div class="footer">
    footer
  </div>
</app-contentdemo>

一般的布局类的组件,都是使用ng-content实现,比如ng-zorror的layout组件,都可以使用ng-content实现

ng-container

ng-container在界面上是没有任何意义的,在浏览器的审查元素中,无法看到它,container意思就是容器。只装东西,不会显示。
<ng-container>
  <h1>test</h1>
</ng-container>

 

 

ng-template

template是模板的意思,ng-template标签主要就是用来加载一个模板。

1
2
3
<ng-template>
  <h2>模板</h2>
</ng-template>

  但是如果是这样,在浏览器中是不会渲染。必须要使用[ngif]=ture或者ngTemplateOutlet才能让模板内容渲染出来

使用[ngif]=true

<ng-template [ngIf]="true" ]>
  <h2>模板</h2>
</ng-template>

 

 使用ngTemplateOutlet

<ng-container *ngTemplateOutlet="greet"></ng-container>
 <ng-template #greet><span>Hello</span></ng-template>

 

 

组件嵌套中的模板上下文

使用primeng的时候,表格组件中,会出现嵌套的ng-template,并能获取到上下文中的对象。这种是怎么做的呢?

在ngTemplateOutlet可以传递一个上下文,直接把对象传递进去的就好了

复制代码
<table style="width: 100%">
  <thead>
  <tr>
    <th *ngFor="let label of labellist">{{label}}</th>
  </tr>
  </thead>
  <tbody>
  <ng-container *ngFor="let item of data;let i = index">
    <tr>

      <ng-container *ngFor="let row of tableColumn">
        <td style="" align="center">
          <ng-container *ngIf="row.prop">
            <label>+</label>
            {{item[row.prop]}}
          </ng-container>
          <ng-container *ngIf="row.scope">
            <ng-container *ngTemplateOutlet="row.scope;context:{row:item}"></ng-container>
          </ng-container>
        </td>
      </ng-container>
    </tr>
  </ng-container>
  </tbody>
</table>
复制代码

使用

复制代码
<app-apptable [data]="data">
  <app-app-col label="用户名" prop="username"></app-app-col>
  <app-app-col label="密码" prop="pwd"></app-app-col>
  <app-app-col label="昵称" prop="pwd"></app-app-col>
  <app-app-col label="测试" scope="scope">
    <ng-template #scope let-data="row">
      <span style="color: red">00-{{data.username}}</span>
    </ng-template>
  </app-app-col>
</app-apptable>
复制代码

在ng-teamplate中 #scope是当前的模板的名字引用,let-xxxx是定义当前的作用域内的用于接受上下文对象的属性,

然后在在模板的作用域类,就可以使用let-xxx的xxx去点出ngTemplateOutlet的context传递的对象。

以上差不多就是我对着三个标签的理解

posted on   快乐海盗  阅读(1498)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示