Angular8自定义结构指令中TemplateRef实例初始化方式咨询
问题解答
是的,templateRef 确实是在构造函数中完成初始化的,这是Angular依赖注入结合TypeScript语法特性实现的。
你在构造函数参数中声明的 private templateRef: TemplateRef<any> 属于 TypeScript带访问修饰符的构造函数参数语法,编译器会自动将这类参数声明为类的实例属性,同时将Angular依赖注入容器注入的对应实例赋值给该属性,不需要额外编写显式初始化代码。
Angular 对结构指令会自动注入两个核心依赖实例:
TemplateRef<any>:指向当前结构指令绑定的宿主元素对应的模板片段,本例中就是<ul>及其子元素组成的模板内容ViewContainerRef:指向模板渲染的视图容器入口,用来控制嵌入视图的创建、清除等操作
你给出的代码逻辑完全符合Angular结构指令开发规范:通过@Input setter监听绑定的渲染次数,清空容器后循环调用createEmbeddedView方法,用注入的templateRef作为模板生成对应数量的DOM节点。
相关代码参考
application.component.html
<ul *appTimes="5"> <li>Hi there!</li> </ul>
time.directive.ts
import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core'; @Directive({ selector: '[appTimes]' }) export class TimesDirective { constructor( private viewContainer: ViewContainerRef, private templateRef: TemplateRef<any> ) { } @Input('appTimes') set render(times: number) { this.viewContainer.clear(); for(let i=0; i < times; i++) { this.viewContainer.createEmbeddedView(this.templateRef, {}); } } }
内容的提问来源于stack exchange,提问作者jadeite1000
相关产品推荐
相关产品推荐

