Skip to main content

通用组件时的扩展性

通用组件再怎么通用,总是会遇到使用的时候想自定义修改一些内容,如果没有提前做好相应的处理,那么此时的通用组件有可能还不如重写一遍,组件的扩展可以通过ng-content和ngTemplateOutlet实现,两者存在一些差异,具体情况具体分析。差异点是ng-content不能展示默认模板,也不能接收组件内部数据,属于简单的,明确知道的可能要自定义的地方。

ng-content

<!-- TestHeaderComponent定义-->
<div class="test">
<div class="left"></div>
<div class="center">
<div class="block-title">{{title}}</div>
<div class="custom">
<!-- 插槽,标签内部的内容会投影插入到这里 -->
<ng-content></ng-content>
</div>
</div>
<div class="right"></div>
</div>
<!-- TestHeaderComponent使用-->
<app-test-header [title]="'测试'">
<button>哈哈</button>
</app-test-header>

ngTemplateOutlet

<!-- TemplateDemoComponent html部分定义-->
<div style="border: 1px solid #00ff00;padding: 24px;">
<ng-template #headDefaule>
<h1>组件默认头部</h1>
</ng-template>
<ng-container *ngTemplateOutlet="headRefExp?headRefExp:headDefaule; context: contextExp"></ng-container>
<div style="border: 1px solid #0ff;">组件内容</div>
</div>
// TemplateDemoComponent ts部分定义
@Input() public headRefExp: TemplateRef<string | HTMLElement>;
// 要暴露出去的数据
contextExp = { $implicit: '这是默认的值', otherValue: "其他值" };
<!-- TemplateDemoComponent 组件使用-->

<!-- 当headRefExp不传的时候,默认会展示默认头部-->
<app-template-demo [headRefExp]="headRefExp"></app-template-demo>

<ng-template #headRefExp let-item let-otherValue="otherValue">
<div>我是自定义的头部</div>
<div>组件内部定义数据------{{item}}</div>
<div>组件内部定义数据------{{valueInContent}}</div>
</ng-template>