[Angular] 笔记 20:NgContent

chatgpt:

在Angular中,NgContent是用于内容投影(Content Projection)的一个重要概念。它允许你在一个组件中插入内容,并将这些内容投影到另一个组件中。

当你在一个组件中使用<ng-content></ng-content>标签时,它充当了一个插槽,可以让你在组件的模板中插入任意HTML内容。这样做的好处是,你可以在组件内部定义模板结构,并允许外部使用该组件时灵活地插入内容,而不是固定在组件内部。

举个例子,假设有一个<app-modal>组件,你希望能够在模态框中放置自定义的内容,而不是在组件内部硬编码。你可以在<app-modal>组件的模板中使用<ng-content></ng-content>标签,这样外部使用<app-modal>组件时,其中的内容就会被投影到<ng-content></ng-content>所在的位置。

ts 复制代码
@Component({
  selector: 'app-modal',
  template: `
    <div class="modal">
      <div class="modal-content">
        <ng-content></ng-content>
      </div>
    </div>
  `,
})
export class ModalComponent {
  // ...
}

然后,当你使用组件时,你可以在其标签内部放置任何内容,这些内容就会被投影到所在的位置。

html 复制代码
<app-modal>
  <h1>Title</h1>
  <p>Modal content goes here...</p>
</app-modal>

这样,<h1>Title</h1><p>Modal content goes here...</p>就会被投影到组件内部模板中的位置。


Angular For Beginners - 24. NgContent

NgContent : a.k.a Content Projection

1. NgContent 单插槽内容投影 :

2. NgContent 多插槽内容投影:

3. detail 使用 NgContent

pokemon-detail.component.html:

html 复制代码
<!-- 将会替代成具体的 html --> 
<ng-content select="h1"></ng-content>

<tr>
  <td class="pokemon-td" [class.cool-bool]="detail.isCool">
    {{ detail.id }} : {{ detail.name }}
    {{ detail.isCool == true ? "is COOL" : "is NOT COOL" }}
  </td>
  <button [routerLink]="['/pokemon', detail.id]">Details</button>
  <button (click)="onRemove()">Remove Pokemon</button>
</tr>

4. list 投影到 detail

pokemon-list.component.html 增加一个 h1元素:

html 复制代码
<table>
  <thead>
    <th>Name</th>
    <th>Index</th>
  </thead>
  <tbody>
    <app-pokemon-detail
      *ngFor="let pokemon of pokemons"
      [detail]="pokemon"
      (remove)="handleRemove($event)"
    ><h1>============================</h1></app-pokemon-detail>
  </tbody>
</table>

5. web 界面

相关推荐
Yanni4Night1 分钟前
使用URLPattern API构建自己的路由器 🛣️
前端·javascript
web守墓人8 分钟前
【前端】garn:使用go实现一款类似yarn的依赖管理器
前端
全栈陈序员14 分钟前
Vue 实例挂载的过程是怎样的?
前端·javascript·vue.js·学习·前端框架
孙严Pay32 分钟前
代付功能的跨界新玩法:不止于金融领域
笔记·科技·计算机网络·其他·微信
好奇龙猫42 分钟前
人工智能学习-AI-MIT公开课-第三节:推理:目标树与基于规则的专家系统-笔记
人工智能·笔记·学习
Bruce_Liuxiaowei1 小时前
一键清理Chrome浏览器缓存:批处理与PowerShell双脚本实现
前端·chrome·缓存
怒放的生命19911 小时前
Vue 2 vs Vue 3对比 编译原理不同深度解析
前端·javascript·vue.js
GDAL1 小时前
html返回顶部实现方式对比
前端·html·返回顶部
Violet_YSWY1 小时前
ES6 () => ({}) 语法解释
前端·ecmascript·es6
LYFlied1 小时前
【每日算法】LeetCode 279. 完全平方数(动态规划)
前端·算法·leetcode·面试·动态规划