【Angular】组件内容嵌入ng-content

前端之家收集整理的这篇文章主要介绍了【Angular】组件内容嵌入ng-content前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

组件的内容嵌入:在组件中嵌入模板代码,提高组件的可复用性。很好得扩充组件的功能,方便代码的服用。典型的例子就是:模态对话框或导航栏的使用,通常模态对话框和导航栏的样式是一样的,这是如果有一个模板,我们只负责往里面填充数据,是不是就方便使用多了,组件内容嵌入就是解决此类问题的。下面举例说明:

文件目录如下:

  1. // example-content.component.ts
  2. import { Component,OnInit } from '@angular/core';
  3.  
  4. @Component({
  5. selector: 'example-content',templateUrl: './example-content.component.html',styleUrls: ['./example-content.component.css'],})
  6. export class ExampleContentComponent implements OnInit {
  7.  
  8. constructor() { }
  9.  
  10. ngOnInit() {
  11. }
  12.  
  13. }

设置模板

  1. <!--example-content.component.html -->
  2. <div>
  3. <table >
  4. <body class="tbody">
  5. <tr >
  6. <td class="header tborder">
  7. <ng-content select="header"></ng-content>
  8. </td>
  9. </tr>
  10.  
  11. <tr>
  12. <td class="body tborder">
  13. <ng-content select=".body"></ng-content>
  14. </td>
  15. </tr>
  16.  
  17. <tr>
  18. <td class="footer tborder">
  19. <ng-content select="[name=footer]"></ng-content>
  20. </td>
  21. </tr>
  22. </body>
  23.  
  24. </table>
  25. </div>
  • 标签:用来渲染组件嵌入的内容
  • 属性select=“header”:select是个选择器,类似于css选择器,它匹配<example-content>标签之间的第一个header**标签**,并把内容填充到ng-content中
  • select=”.body”:使用了类选择器来指定ng-content,“.body”是<example-content>标签的一个class名字
  • select=”[name=footer]”:使用了属性选择器来指定ng-content,“footer”是<example-content>标签的一个name名字
    注意三者select的写法

模板样式

  1. // example-content.component.css
  2. .tbody {
  3. border: 1px solid;
  4. border-collapse: collapse;
  5. }
  6. .tborder{
  7. border: 1px solid ;
  8.  
  9. }
  10. .header{
  11. background-color: rgb(189,187,187);
  12. }
  13. .body {
  14. height: 100px;
  15. width: 200px;
  16. }
  17. .footer{
  18. background-color:rgb(189,187);
  19. }

为模板添加内容

  1. <!--app.component.html-->
  2. <example-content >
  3. <header>联系人</header>
  4. <div class="body">
  5. 李四:18766892869
  6. </div>
  7. <div name="footer">
  8. 查看详情请点击联系人
  9. </div>
  10. </example-content>
  • 标签必须是模板中selector的指定标签
  • <example-content >标签之间的内容被填充到了ng-content中,

运行后得到如图

如果别的程序想用这个样式,只需改变一下内容:只需改动引用该模板样式的模板,如

  1. <!--app.component.html-->
  2. <example-content >
  3. <header>商店</header>
  4. <div class="body">
  5. 水果类
  6. </div>
  7. <div name="footer">
  8. 由霜有限公司提供
  9. </div>
  10. </example-content>

运行结果如下

猜你在找的Angularjs相关文章