我见过很多ElemenetRef和TemplateRef的例子让我更加困惑.
> ElementRef和TemplateRef之间的区别是什么我们应该使用另一个
<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;
所以我的问题是为什么我应该使用TemplateRef,如果我可以使用ElementRef实现相同的
解决方法
ElementRef就像document.getElementById(‘myId’);
通过ElementRef你只能做一些装饰
TemplateRef是一个嵌入式模板,您可以将其赋予角度以创建嵌入式视图.
* ng为了做同样的事情,它将元素读取为TemplateRef并注入多次以创建带有数据的视图
TemplateRef不能用作.ts中css装饰的元素