angular4中的ElemenetRef和TemplateRef之间的区别
发布时间:2020-12-17 17:12:01 所属栏目:安全 来源:网络整理
导读:我见过很多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 el
我见过很多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; 所以我的问题是为什么我应该使用TemplateRef,如果我可以使用ElementRef实现相同的 解决方法
ElementRef就像document.getElementById(‘myId’);
通过ElementRef你只能做一些装饰 TemplateRef是一个嵌入式模板,您可以将其赋予角度以创建嵌入式视图. * ng为了做同样的事情,它将元素读取为TemplateRef并注入多次以创建带有数据的视图 TemplateRef不能用作.ts中css装饰的元素 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读