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传递的对象。
以上差不多就是我对着三个标签的理解
分类:
前端笔记
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端