组件的内容嵌入:在组件中嵌入模板代码,提高组件的可复用性。很好得扩充组件的功能,方便代码的服用。典型的例子就是:模态对话框或导航栏的使用,通常模态对话框和导航栏的样式是一样的,这是如果有一个模板,我们只负责往里面填充数据,是不是就方便使用多了,组件内容嵌入就是解决此类问题的。下面举例说明:
文件目录如下:
- // example-content.component.ts
- import { Component,OnInit } from '@angular/core';
-
- @Component({
- selector: 'example-content',templateUrl: './example-content.component.html',styleUrls: ['./example-content.component.css'],})
- export class ExampleContentComponent implements OnInit {
-
- constructor() { }
-
- ngOnInit() {
- }
-
- }
设置模板:
- <!--example-content.component.html -->
- <div>
- <table >
- <body class="tbody">
- <tr >
- <td class="header tborder">
- <ng-content select="header"></ng-content>
- </td>
- </tr>
-
- <tr>
- <td class="body tborder">
- <ng-content select=".body"></ng-content>
- </td>
- </tr>
-
- <tr>
- <td class="footer tborder">
- <ng-content select="[name=footer]"></ng-content>
- </td>
- </tr>
- </body>
-
- </table>
- </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的写法
模板样式:
- // example-content.component.css
- .tbody {
- border: 1px solid;
- border-collapse: collapse;
- }
- .tborder{
- border: 1px solid ;
-
- }
- .header{
- background-color: rgb(189,187,187);
- }
- .body {
- height: 100px;
- width: 200px;
- }
- .footer{
- background-color:rgb(189,187);
- }
- <!--app.component.html-->
- <example-content >
- <header>联系人</header>
- <div class="body">
- 李四:18766892869
- </div>
- <div name="footer">
- 查看详情请点击联系人
- </div>
- </example-content>
运行后得到如图:
如果别的程序想用这个样式,只需改变一下内容:只需改动引用该模板样式的模板,如
- <!--app.component.html-->
- <example-content >
- <header>商店</header>
- <div class="body">
- 水果类
- </div>
- <div name="footer">
- 由霜有限公司提供
- </div>
- </example-content>
运行结果如下: