angular4中ElementRef和TemplateRef之间的区别 [英] Difference between ElementRef and TemplateRef in angular4

查看:627
本文介绍了angular4中ElementRef和TemplateRef之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了许多ElemenetRef和TemplateRef的例子,这让我更加困惑.

i have seen many examples of ElemenetRef and TemplateRef which got me more confused.

  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,那么它也可以正常工作

now if i change the above code to use ElementRef then also it works fine

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

所以我的问题是,如果我可以通过使用ElementRef达到相同的效果,为什么我应该使用TemplateRef

so my question is why should i use TemplateRef if i can acheive the same with the use of ElementRef

推荐答案

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

使用ElementRef您只能做一些装饰

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

TemplateRef is an embedded template which you can use in ViewContainerRef.createEmbeddedView to create Embedded View.

*ngFor与此相同,它将元素读取为TemplateRef并多次注入以创建具有数据的视图

*ngFor is doing the same, it reads the element as a TemplateRef and injects mutiple times to create view with data

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

TemplateRef cannot be used as an element for css decorations in .ts

这篇关于angular4中ElementRef和TemplateRef之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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