i have seen many examples of ElemenetRef and TemplateRef which got me more confused.
- what is the difference between ElementRef and TemplateRef why we should use one over another
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 file
@ViewChild('element', { read: TemplateRef }) element: TemplateRef<any>;
@ViewChild('template', { read: ViewContainerRef }) template: ViewContainerRef;
ngAfterViewInit() {
this.template.createEmbeddedView(this.element);
}
now if i change the above code to use ElementRef then also it works fine
@ViewChild('element', { read: ElementRef }) element: ElementRef;
so my question is why should i use TemplateRef if i can acheive the same with the use of ElementRef
ElementRef
refers to an element of the DOM, whereasTemplateRef
represents an embedded template (usually a component template). So to summarize, the template ref can contain several element refs, but the element ref can not contain a template ref. – Shabby<app-my-component #templateRef><div #elementRef>Some content</div></app-my-component>
. The template reference is to be used only with view container references, most of the time in structural directives (directives like*ngFor
or*ngIf
that manipulate the DOM directly). The documentation about ElementRef, TemplateRef and structural directives mght help you. – ShabbytemplateRef is better than ElementRef because ...
isn't possible, because they both serve different purposes. – Shabby