【问题标题】:Difference between ElementRef and TemplateRef in angular4angular4中ElementRef和TemplateRef的区别
【发布时间】:2019-04-21 19:13:21
【问题描述】:

我见过很多 ElemenetRef 和 TemplateRef 的例子,这让我更加困惑。

  1. ElementRef 和 TemplateRef 有什么区别,为什么我们应该使用一个而不是另一个

HTML

<ng-template #element>
  <div style="border:solid 3px yellow;width:250px;
height:250px;position:relative;top:0px;">
    this is my element
  </div>

</ng-template>
<ng-container #template>

</ng-container>

.ts 文件

@ViewChild('element', { read: TemplateRef }) element: TemplateRef<any>;
  @ViewChild('template', { read: ViewContainerRef }) template: ViewContainerRef;

 ngAfterViewInit() {
    this.template.createEmbeddedView(this.element);
  }

现在,如果我将上面的代码更改为使用 ElementRef,那么它也可以正常工作

@ViewChild('element', { read: ElementRef }) element: ElementRef;

所以我的问题是,如果我可以通过使用 ElementRef 实现相同的效果,我为什么要使用 TemplateRef

【问题讨论】:

  • ElementRef 指的是 DOM 的一个元素,而TemplateRef 表示一个嵌入的模板(通常是组件模板)。综上所述,模板引用可以包含多个元素引用,但元素引用不能包含模板引用。
  • 所以如果我们有一个像这样的简单 dom那么我们必须使用 elementRef 并且如果我们有一个像这样的模板
    something here
    那么我们必须使用templateRef,对吗?如果是,那么 templateRef 能做什么,而 elementRef 不能,你能不能给我一个简短的想法,我无法在网上找到任何关于此的内容
  • 在 HTML 中它给出了&lt;app-my-component #templateRef&gt;&lt;div #elementRef&gt;Some content&lt;/div&gt;&lt;/app-my-component&gt;。模板引用只能与视图容器引用一起使用,大部分时间在结构指令中(像 *ngFor*ngIf 这样直接操作 DOM 的指令)。有关ElementRefTemplateRefstructural directives 的文档对您有所帮助。
  • 现在 viewContainerRef 也有一个与 templateRef 相同的 createEmbeddedView() 方法。那么当我可以使用 viewContainerRef 并使用 elementRef 获取元素时,为什么还要使用 templateRef
  • 你在这里摆脱了原来的问题。不要把它变成XY problem:告诉我你想要达到的目标,我会告诉你怎么做。

标签: angular elementref


【解决方案1】:

ElementRef 就像document.getElementById('myId');

使用ElementRef你只能做一些装饰

TemplateRef 是一个嵌入式模板,您可以在ViewContainerRef.createEmbeddedView 中使用它来创建嵌入式视图。

*ngFor 也在做同样的事情,它将元素读取为 TemplateRef 并注入多次以创建带有数据的视图

TemplateRef 不能用作 .ts 中的 css 装饰元素

【讨论】:

  • @trichetriche,你能告诉我这个答案是否正确,谢谢
【解决方案2】:

元素参考

  1. 用于基本的 DOM 抽象。

  2. 我们可以访问 DOM 中存在的基本原生元素。

模板参考

  1. 用于访问模板内的DOM元素。

  2. 结构指令使用此 TemplateRef。

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签