Angular动态ngTemplateOutlet使用问题求助
解决动态ngTemplateOutlet匹配模板的问题
问题核心是:*ngTemplateOutlet接收的是TemplateRef实例,你数组里的"DELETE"、"MODIFY"是字符串,类型不匹配,所以无法关联到对应的模板。
实现步骤:
- 组件类中获取模板引用并建立映射
在组件的.ts文件中,通过@ViewChild获取每个模板的实例,再创建一个映射对象把字符串名称和模板实例绑定:
import { Component, ViewChild, TemplateRef } from '@angular/core'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', styleUrls: ['./your-component.component.css'] }) export class YourComponent { actions = ["DELETE", "MODIFY"]; // 存储字符串到模板实例的映射 templateMap: { [key: string]: TemplateRef<any> } = {}; @ViewChild('DELETE') deleteTemplate!: TemplateRef<any>; @ViewChild('MODIFY') modifyTemplate!: TemplateRef<any>; ngAfterViewInit() { // 初始化映射关系 this.templateMap['DELETE'] = this.deleteTemplate; this.templateMap['MODIFY'] = this.modifyTemplate; } }
- 模板中动态引用映射后的模板实例
在HTML里通过映射对象获取对应TemplateRef实例,传给*ngTemplateOutlet:
<ng-container *ngFor="let action of actions"> <ng-container *ngTemplateOutlet="templateMap[action]; context:{item: item}"></ng-container> </ng-container> <ng-template #DELETE let-item="item">delete {{item?.id}}</ng-template> <ng-template #MODIFY let-item="item">modify {{item?.name}}</ng-template>
补充说明:
- 后续新增模板时,只需要在组件中添加对应的
@ViewChild,并在templateMap里补充映射即可,完全不需要手动写条件判断,保持动态性。 - 必须在
ngAfterViewInit钩子中初始化映射:只有视图初始化完成后,才能通过ViewChild获取到模板实例。
内容的提问来源于stack exchange,提问作者noobie
相关产品推荐
相关产品推荐

