如何在组件代码中声明TemplateRef实例以在模板中多次复用?
Angular 复用通用模板避免代码冗余
问题场景
有多个app-lookup组件实例,每个需要传入完全相同的模板内容,为避免重复编写模板代码,希望实现模板复用。
当前冗余代码示例
<app-lookup [data]="lookupData[0]"> <ng-template let-ctx>{{ctx.name}} ...</ng-template> </app-lookup> ... <app-lookup [data]="lookupData[99]"> <ng-template let-ctx>{{ctx.name}} ...</ng-template> </app-lookup>
正确实现方案
1. 定义共享模板并循环渲染
在组件模板中先定义一次共享模板,通过#template标记,再结合*ngFor循环渲染app-lookup,用ngTemplateOutlet复用模板:
<!-- 定义共享模板 --> <ng-template #template let-ctx> {{ctx.name}} ... </ng-template> <!-- 循环渲染所有app-lookup,复用模板 --> <app-lookup *ngFor="let dataItem of lookupData" [data]="dataItem" > <ng-container [ngTemplateOutlet]="template"></ng-container> </app-lookup>
注意:你之前拼写的
ngTempalteOutput是错误的,正确指令为ngTemplateOutlet。
2. 组件代码中获取模板引用
无需手动初始化模板,通过@ViewChild获取当前组件内定义的模板引用即可:
import { Component, ViewChild, TemplateRef } from '@angular/core'; @Component({ selector: 'your-component', templateUrl: './your-component.component.html' }) export class YourComponent { // 你的数据源 lookupData = []; // 获取共享模板引用,Angular会自动赋值,无需手动初始化 @ViewChild('template') template!: TemplateRef<unknown>; }
关键说明
@ViewChild用于获取当前组件内部定义的模板/元素引用,而@ContentChild是用来获取父组件通过内容投影传入的内容,你的场景用@ViewChild更合适。- 非空断言
!用于告诉TypeScript该属性会在组件初始化后被赋值,避免类型报错。
内容的提问来源于stack exchange,提问作者Konrad Viltersten
相关产品推荐
相关产品推荐

