Angular 11中如何在父组件中单独显示子组件内的筛选元素?
解决方案
步骤1:改造子组件的模板结构
把原来的DOM容器换成ng-template(因为*ngTemplateOutlet需要的是TemplateRef实例,而非普通DOM元素),同时保留模板引用标识:
<!-- table-filters.component.html --> <form> <!-- 在原form中渲染筛选器模板 --> <ng-container *ngTemplateOutlet="companyFilter"></ng-container> <ng-container *ngTemplateOutlet="otherFilter"></ng-container> </form> <!-- 把筛选器内容定义为独立模板 --> <ng-template #companyFilter> <!-- 原companyFilter的内容 --> ... </ng-template> <ng-template #otherFilter> <!-- 原otherFilter的内容 --> ... </ng-template>
步骤2:子组件类中暴露模板引用
通过@ViewChild获取模板实例,并将其作为公共属性暴露,供父组件访问:
// table-filters.component.ts import { Component, ViewChild, TemplateRef } from '@angular/core'; @Component({ selector: 'table-filters', templateUrl: './table-filters.component.html' }) export class TableFiltersComponent { // 获取两个筛选器的模板引用 @ViewChild('companyFilter') companyFilterTemplate!: TemplateRef<any>; @ViewChild('otherFilter') otherFilterTemplate!: TemplateRef<any>; }
步骤3:父组件中引用子组件的模板
给子组件添加模板引用变量,通过该变量直接访问子组件暴露的模板实例,再用*ngTemplateOutlet在表格内渲染:
<!-- 父组件模板 --> <!-- 给子组件添加引用变量#filterComp --> <table-filters #filterComp></table-filters> <table> ... <!-- 渲染子组件中的筛选器模板 --> <ng-container *ngTemplateOutlet="filterComp.companyFilterTemplate"></ng-container> <ng-container *ngTemplateOutlet="filterComp.otherFilterTemplate"></ng-container> </table>
说明
- 这种方式无需为每个筛选器单独创建组件,只需将筛选器内容封装为
ng-template即可实现复用。 - 子组件内部通过
*ngTemplateOutlet仍可在原form中渲染筛选器,不影响原有功能。
内容的提问来源于stack exchange,提问作者SyncroIT
相关产品推荐
相关产品推荐

