如何不使用ViewChildren直接从HTML获取多个TemplateRef的QueryList集合?
Angular 原生不支持直接在 HTML 模板中生成 QueryList<TemplateRef> 类型的值直接传入子组件,QueryList 是 Angular 内部为视图/内容查询能力设计的专用类,只能通过 @ViewChildren、@ContentChildren 这类查询装饰器生成。
不过有两个完全符合你需求的替代方案,不需要在父组件中使用 @ViewChildren:
方案1:父组件直接传递模板数组
适合模板数量固定的场景,直接把多个模板引用组装成数组传入子组件即可:
父组件 HTML 代码
<ng-template #tpl1 let-param> ... </ng-template> <ng-template #tpl2 let-param> ... </ng-template> <!-- 手动组装模板数组传入子组件 --> <app-my-component [inputTemplates]="[tpl1, tpl2]"></app-my-component>
子组件 TS 代码
import { Component, Input, SimpleChanges, OnChanges, TemplateRef } from '@angular/core'; @Component({ selector: 'app-my-component', templateUrl: './my-component.component.html' }) export class MyComponentComponent implements OnChanges { @Input() inputTemplates: TemplateRef<any>[] = []; // 如果需要监听模板列表变化,可实现 ngOnChanges 钩子 ngOnChanges(changes: SimpleChanges) { if (changes.inputTemplates) { // 处理模板列表更新逻辑 } } }
方案2:子组件通过内容投影自主查询(推荐)
这个方案可以直接拿到你需要的 QueryList<TemplateRef> 类型,全程不需要父组件做任何查询操作:
父组件 HTML 代码
把所有需要传入的模板放到子组件标签内部即可:
<app-my-component> <ng-template #customHeaderTemplate let-param> ... </ng-template> <ng-template #customHeaderTemplate let-param> ... </ng-template> </app-my-component>
子组件 TS 代码
子组件自己通过 @ContentChildren 查询内部投影的模板,直接得到 QueryList 对象:
import { Component, ContentChildren, QueryList, TemplateRef, AfterContentInit } from '@angular/core'; @Component({ selector: 'app-my-component', templateUrl: './my-component.component.html' }) export class MyComponentComponent implements AfterContentInit { // 直接查询所有带 customHeaderTemplate 引用的模板,得到 QueryList @ContentChildren('customHeaderTemplate') customHeaderTemplates: QueryList<TemplateRef<any>>; ngAfterContentInit() { // 初始模板列表加载完成,可以直接使用 console.log(this.customHeaderTemplates); // 订阅 changes 事件,监听模板动态增删的变化 this.customHeaderTemplates.changes.subscribe(newTplList => { // 模板列表更新后的处理逻辑 }); } }
内容的提问来源于stack exchange,提问作者shuangyu chen
相关产品推荐
相关产品推荐

