javascript – Angular 2了解ViewContainerRef与TemplateRef的用法

我正在Angular2中实现结构指令.

在文档中,我看到我需要注入TemplateRef来获取模板元素和ViewContainerRef.

class TestDirective {
   constructor( private templateRef : TemplateRef<any>, private viewContainer : ViewContainerRef ) {
     // this.viewContainer.createEmbeddedView(this.templateRef);
   }   
}

<template [ngIf]="condition">
  <p>
    Our heroes are true!
  </p>
</template>

在这种情况下,我不明白哪个元素是ViewContainerRef?

最佳答案 如果注入ViewContainerRef,则元素是TestDirective的宿主元素.如果使用@ViewChild(templateVarNameOrType)或@ContentChild(templateVarNameOrType),则它是templateVarNameOrType匹配的元素.

您应该知道this.viewContainer.createEmbeddedView()或this.viewContainer.createComponent()创建元素或组件作为ViewContainerRef指向的元素的兄弟,而不是像child一样期望的元素.

点赞