[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 界面

相关推荐
恋猫de小郭6 分钟前
为什么跨平台框架可以适配鸿蒙,它们的技术原理是什么?
android·前端·flutter
云浪10 分钟前
元素变形记:CSS 缩放函数全指南
前端·css
明似水25 分钟前
用 Melos 解决 Flutter Monorepo 的依赖冲突:一个真实案例
前端·javascript·flutter
m0_6371469333 分钟前
计算机网络基础总结:TCP/IP 模型、TCP vs UDP、DNS 查询过程
笔记·tcp/ip·计算机网络
独立开阀者_FwtCoder35 分钟前
stagewise:让AI与代码编辑器无缝连接
前端·javascript·github
清沫37 分钟前
Cursor Rules 开发实践指南
前端·ai编程·cursor
江城开朗的豌豆42 分钟前
JavaScript篇:对象派 vs 过程派:编程江湖的两种武功心法
前端·javascript·面试
不吃糖葫芦343 分钟前
App使用webview套壳引入h5(二)—— app内访问h5,顶部被手机顶部菜单遮挡问题,保留顶部安全距离
前端·webview
Lester_11011 小时前
嵌入式学习笔记 - freeRTOS vTaskPlaceOnEventList()函数解析
笔记·学习
江城开朗的豌豆1 小时前
JavaScript篇:字母侦探:如何快速统计字符串里谁才是'主角'?
前端·javascript·面试