Skip to content

Instantly share code, notes, and snippets.

@rajaramtt
Last active February 18, 2019 18:18
Show Gist options
  • Save rajaramtt/63a97ef8f82ca9b9dfdaef52c362e2d2 to your computer and use it in GitHub Desktop.
Save rajaramtt/63a97ef8f82ca9b9dfdaef52c362e2d2 to your computer and use it in GitHub Desktop.
Difference between Renderer and ElementRef in angular 2 / ElementRef vs. ViewContainerRef vs. TemplateRef
The Renderer is a class that is a partial abstraction over the DOM. Using the Renderer for manipulating the DOM doesn't break server-side rendering or Web Workers (where direct access to the DOM would break).
ElementRef is a class that can hold a reference to a DOM element. This is again an abstraction to not break in environments where the browsers DOM isn't actually available.
If ElementRef is injected to a component, the injected instance is a reference to the host element of the current component.
There are other ways to acquire an ElementRef instance like @ViewChild(), @ViewChildren(), @ContentChild(), @ContentChildren(). In this case ElementRef is a reference to the matching element(s) in the template or children.
Renderer and ElementRef are not "either this or that", but instead they have to be used together to get full platform abstraction.
Renderer acts on the DOM and ElementRef is a reference to an element in the DOM the Renderer acts on.
------------------------------------------------------------
ElementRef is simply a like document.getElementById('myId');
by ElementRef you can only able to do some decorations
TemplateRef is a embedded template where you can give it to angular to create Embedded View.
*ngFor doing the same, it reads the element as TemplateRef and injects mutiple times to create view with data
TemplateRef cannot be used as a element for css decorations in .ts
--------------------------------------------------------------------
If you ever needed to insert new component or template programmatically, you probably used the ViewContainerRef service.
https://chaoyang.nz/post/elementref-viewcontainerref-templateref/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment