浅谈Angular如何使用ng-content进行内容投影


本文摘自PHP中文网,作者青灯夜游,侵删。

在这篇文章中,我们将会探索如何使用 ng-content 进行内容投影,来创建灵活的可复用组件。

ng-content

ng-content 元素是一个用来插入外部或者动态内容的占位符。父组件将外部内容传递给子组件,当 Angular 解析模板时,就会在子组件模板中 ng-content 出现的地方插入外部内容。

我们可以使用内容投影来创建可重用的组件。这些组件有相似的逻辑和布局,并且可以在许多地方使用。一般我们在封装一些公共组件的时候经常会用到。【相关教程推荐:《angular教程》】

不使用内容投影

为了理解为什么要使用 ng-content 进行内容投影,首先让我们来创建一个很常见的 button 组件。

btn.component.ts

1

2

3

4

5

6

7

8

9

10

11

12

13

14

import { Component } from '@angular/core';

 

@Component({

  selector: 'app-btn',

  templateUrl: './btn.component.html',

  styleUrls: ['./btn.component.scss'],

})

export class BtnComponent {

  constructor() {}

 

  onClick($event: any) {

    console.log($event);

  }

}

btn.component.html

1

2

3

<button (click)=onClick($event)>

  Click Me

</button>

在这个组件中,button 的文本始终是 Click Me,如果我们想传递不同的文本进来呢?可能你会想到最常使用的 @Input 装饰器,但是如果我们不只是想传文本进来,而是传一段 html 进来呢?这个时候就需要用到这篇文章的主角:ng-content

单插槽内容投影

内容投影的最基本形式是单插槽内容投影。单插槽内容投影是指创建一个组件,我们可以在其中投影一个组件。

要创建使用单插槽内容投影的组件,我们只需要对上面的组件进行一些简单的修改:把 Click Me 替换为 <ng-content></ng-content>

btn.component.html

1

2

3

<button (click)=onClick($event)>

  <ng-content></ng-content>

</button>

在使用 btn 组件的地方:

1

2

<app-btn>Cancel</app-btn>

<app-btn><b>Submit</b></app-btn>

<app-btn></app-btn> 中的内容会传递给 btn 组件,并且显示在 ng-contnet 中。

多插槽内容投影

上面的 btn 组件非常简单,但实际上ng-content 要比这个更强大。一个组件可以具有多个插槽,每个插槽可以指定一个 CSS 选择器,该选择器会决定将哪些内容放入该插槽。该模式称为多插槽内容投影。使用此模式,我们必须指定希望投影内容出现在的位置。可以通过使用 ng-contentselect 属性来完成此任务。

要创建使用多插槽内容投影的组件,需要执行以下操作:

  • 创建一个组件。

  • 在组件模板中,添加 ng-content 元素,让你希望投影的内容出现在其中。

  • select 属性添加到 ng-content 元素。 Angular 使用的选择器支持标签名、属性、CSS 类和 :not 伪类的任意组合。

下面我们来创建一个复杂一些的 card 组件。

card.component.html

1

2

3

4

5

6

7

8

9

10

11

<div class="card">

  <div class="header">

    <ng-content select="header"></ng-content>

  </div>

  <div class="content">

    <ng-content select="content"></ng-content>

  </div>

  <div class="footer">

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

  </div>

</div>

在使用 card 组件的地方:

app.component.html

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<app-card>

  <header>

    <h1>Angular</h1>

  </header>

  <content>One framework. Mobile & desktop.</content>

  <footer><b>Super-powered by Google </b></footer>

</app-card>

 

<app-card>

  <header>

    <h1 style="color:red;">React</h1>

  </header>

  <content>A JavaScript library for building user interfaces</content>

  <footer><b>Facebook Open Source </b></footer>

</app-card>

如果在 app-card 中有不属于 header, content, footer 之外的内容呢?比如按照下面的写法使用 app-card 组件:

阅读剩余部分

相关阅读 >>

浅谈Angular中父子组件间怎么传递数据

谈谈Angular模块的使用以及懒加载

2021年值得尝试的7个Angular前端组件库,快来收藏吧!

详解Angular中的组件交互

浅谈Angular组件的交互方式

聊聊Angular中的模板输入变量(let-变量)

Angular实现只执行正在开发的新单元测试

浅谈Angular中父子组件间相互传参的方法

Angular组件学习之浅析内容投影

Angular中的firebase身份验证(代码示例)

更多相关阅读请进入《Angular》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...