【问题标题】:Angular 2 understand ViewContainerRef usage with TemplateRefAngular 2 通过 TemplateRef 了解 ViewContainerRef 的使用
【发布时间】:2016-10-24 22:42:33
【问题描述】:

我正在 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 是哪个元素?

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    如果您注入ViewContainerRef,则该元素是TestDirective 的宿主元素。如果您使用@ViewChild(templateVarNameOrType)@ContentChild(templateVarNameOrType),则它是templateVarNameOrType 匹配的元素。

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

    【讨论】:

    • 您可以通过示例扩展您的答案,我看到很多人都在为这个问题而苦苦挣扎。谢谢。
    • @ViewChild(templateVarNameOrType) 或 @ContentChild(templateVarNameOrType),你有重复 this.viewContainer.createEmbeddedView() 代码
    • 感谢您的提示。是复制粘贴错误。也许stackoverflow.com/questions/32693061/… 填补了缺失的空白。
    • 如果我需要在小时候创建元素怎么办?
    • 您需要一个子元素内部的ViewContainerRef,但我不知道有什么方法可以得到它,除非子元素提供了一个它自己通过@ViewChild() 获取的元素。
    猜你喜欢
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 2017-07-16
    相关资源
    最近更新 更多