我看过很多 ElemenetRef 和 TemplateRef 的例子,这让我更加困惑。
- 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
就像 document.getElementById('myId')
;
使用 ElementRef
你只能做一些装饰
TemplateRef
是一个嵌入式模板,您可以在 ViewContainerRef.createEmbeddedView
中使用它来创建嵌入式 View 。
*ngFor
也在做同样的事情,它将元素读取为 TemplateRef
并多次注入(inject)以创建带有数据的 View
TemplateRef
不能作为.ts中css装饰的元素
关于angular - angular4 中 ElementRef 和 TemplateRef 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53374430/