【Angular】组件内容嵌入ng-content
发布时间:2020-12-17 08:31:49 所属栏目:安全 来源:网络整理
导读:组件的内容嵌入:在组件中嵌入模板代码,提高组件的可复用性。很好得扩充组件的功能,方便代码的服用。典型的例子就是:模态对话框或导航栏的使用,通常模态对话框和导航栏的样式是一样的,这是如果有一个模板,我们只负责往里面填充数据,是不是就方便使用
组件的内容嵌入:在组件中嵌入模板代码,提高组件的可复用性。很好得扩充组件的功能,方便代码的服用。典型的例子就是:模态对话框或导航栏的使用,通常模态对话框和导航栏的样式是一样的,这是如果有一个模板,我们只负责往里面填充数据,是不是就方便使用多了,组件内容嵌入就是解决此类问题的。下面举例说明: 文件目录如下: // 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>
模板样式: // 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>
运行结果如下: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |