Angular 2了解ViewContainerRef与TemplateRef的用法 [英] Angular 2 understand ViewContainerRef usage with TemplateRef

查看:120
本文介绍了Angular 2了解ViewContainerRef与TemplateRef的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Angular2 中实现结构指令。
在文档中,我看到我需要注入 TemplateRef 来获取模板元素和 ViewContainerRef

I am implementing the structural directive in Angular2. In the docs, I saw that I need to inject the TemplateRef to get the template element and the 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

In this case what I don't understand which element is the ViewContainerRef?

推荐答案

如果你注入 ViewContainerRef element是 TestDirective 的主机元素。如果您使用 @ViewChild(templateVarNameOrType) @ContentChild(templateVarNameOrType)它是的元素templateVarNameOrType 匹配。

If you inject ViewContainerRef the element is the host element of TestDirective. If you use @ViewChild(templateVarNameOrType) or @ContentChild(templateVarNameOrType) it's the element where templateVarNameOrType matches.

你应该知道 this.viewContainer.createEmbeddedView() this.viewContainer.createComponent()创建元素或组件作为 ViewContainerRef 元素的兄弟,而不是很多人都期待孩子。

You should be aware that this.viewContainer.createEmbeddedView() or this.viewContainer.createComponent() creates the element or component as sibling of the element ViewContainerRef points to, not as many expect as child.

这篇关于Angular 2了解ViewContainerRef与TemplateRef的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆