Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ElementRef and TemplateRef in angular4

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

  1. 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

like image 807
Lijin Durairaj Avatar asked Nov 19 '18 12:11

Lijin Durairaj


2 Answers

ElementRef is simply like document.getElementById('myId');

Using ElementRef you are only able to do some decorations

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

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

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

like image 162
Sheik Althaf Avatar answered Nov 07 '22 13:11

Sheik Althaf


ElementRef

  1. Used for basic DOM abstraction.

  2. We can access basic native element present in DOM.

TemplateRef

  1. Used to access DOM element within template.

  2. Structural directive uses this TemplateRef.

like image 34
shubham soni Avatar answered Nov 07 '22 13:11

shubham soni