Angular 14中ng-template参数的严格类型定义方法
Angular 14中ng-template参数的正确类型
在Angular 14里,你传递的<ng-template>对应的正确类型是TemplateRef,需要从@angular/core模块导入。泛型部分可根据模板是否需要上下文来指定,若无需上下文,用unknown或any即可。
修改后的component.ts代码示例:
import { TemplateRef } from '@angular/core'; // ... public myfn(template: TemplateRef<unknown>): void { // 这里可以安全地操作template,比如传入模态框组件等 }
补充说明
TemplateRef是Angular提供的专门用于表示<ng-template>实例的类型,替换any能获得更好的类型检查和IDE提示。- 如果你的模板需要接收上下文数据(比如使用
let-*语法),可以把泛型替换为对应的上下文类型,比如TemplateRef<{ item: string }>。
内容的提问来源于stack exchange,提问作者Midhun
相关产品推荐
相关产品推荐

