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


当前第2页 返回上一页

app.component.html

1

2

3

4

5

6

7

8

9

<app-card>

  <header>

    <h1>Angular</h1>

  </header>

  <div>Not match any selector</div>

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

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

  <div>This text will not not be shown</div>

</app-card>

会发现两个 div 都没有渲染在页面中,为了解决这个问题,我们可以在组件中添加一个没有任何 selectorng-content 标签。所有没办法匹配到任何其他插槽的内容都会被渲染在这个里面。

card.component.html

1

2

3

4

5

6

7

8

9

10

11

12

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

  <ng-content></ng-content>

</div>

ngProjectAs

在某些情况下,我们需要使用 ng-container 把一些内容包裹起来传递到组件中。大多数情况是因为我们需要使用结构型指令像 ngIf 或者 ngSwitch 等。比如只有在某些情况下才向 card 组件传递 header。

在下面的例子中,我们将 header 包裹在了 ng-container 中。

1

2

3

4

5

6

7

8

9

<app-card>

  <ng-container>

    <header>

      <h1>Angular</h1>

    </header>

  </ng-container>

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

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

</app-card>

由于 ng-container 的存在,header 部分并没有被渲染到我们想要渲染的插槽中,而是渲染到了没有提供任何 selector 的 ng-content 中。

在这种情况下,我们可以使用 ngProjectAs 属性。

在上面的 ng-container 加上这个属性,就可以按照我们的期望来渲染了。

1

2

3

4

<app-card>

  <ng-container ngProjectAs='header'>

    ...

</app-card>

更多编程相关知识,请访问:编程教学!!

以上就是浅谈Angular如何使用ng-content进行内容投影的详细内容,更多文章请关注木庄网络博客

返回前面的内容

相关阅读 >>

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

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

聊聊Angular中的单元测试

深入了解Angular中的pipe(管道)

浅谈Angular中控制器、服务和指令的关系

浅谈Angular中的变化检测(change detection)

详解Angular中jsencrypt插件的使用方法

浅谈Angular cli工具如何从零搭建并运行一个简单项目

浅谈Angular10配置@路径别名的方法

10个从喜到悲的Angular面试题

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




打赏

取消

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

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

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

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

评论

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