[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>所在的位置。

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

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

<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 --> 
<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元素:

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

在这里插入图片描述

相关推荐

  1. Angular 2 学习笔记

    2024-01-01 22:02:02       36 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-01 22:02:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-01 22:02:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-01 22:02:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-01 22:02:02       18 阅读

热门阅读

  1. Linux:20个linux常用命令

    2024-01-01 22:02:02       40 阅读
  2. js获取某天日期

    2024-01-01 22:02:02       32 阅读
  3. 国内低代码平台介绍及优势盘点

    2024-01-01 22:02:02       33 阅读
  4. 微服务(8)

    2024-01-01 22:02:02       33 阅读
  5. Golang标准库sync的使用

    2024-01-01 22:02:02       35 阅读
  6. 源码解析:mybatis调用链之获取sqlSession

    2024-01-01 22:02:02       33 阅读
  7. 浅析 Dockerfile 构建缓存:原理与优化方法

    2024-01-01 22:02:02       39 阅读