Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

ElementRef vs Renderer - Angular 2

What are the difference between Renderer and Elementref in angular 2?

ElementRef vs. Renderer -
In Angular Renderer and ElementRef are used for DOM Manipulation and Renderer and ElementRef are used together to get full platform abstraction.

Renderer is a class that is a partial abstraction done the Dom Manipulations and the DOM manipulating is not breaking server side rendering or web workers.

ElementRef –
ElementRef is a class that is a partial abstraction done the DOM Manipulations without breakable environments and it also can hold a reference to a DOM elements.

If “ElementRef” is injected to a component, the injected instance is a reference to the host element of the current component.

The ways to get an ElementRef instance looks like,
1.     @ViewChild()
2.     @ViewChildren()
3.     @ContentChild()
4.     @ContentChildren()

In this case the ElementRef is a reference to the matching elements in the templates.

Do notice that you should refrain from using ElementHref as it flagged with a security risk?
If you allow direct access to the DOM, it can make your application more vulnerable to XSS attacks. So make sure, when you are using to ElementRef in your app code.

What is the point of calling renderer.invokeElementMethod(rendererEl, methodName)?

//our root app component
import {Component, ElementRef} from 'angular2/core'
import * as browser from 'angular2/platform/browser'
import {Ruler, Rectangle} from 'angular2/src/platform/browser/ruler.js'

selector: 'my-app',
providers: [ElementRef],
template: `
h2>Hello {{name}}/h2>
p>H2 Height: {{rect.height}}/p>
p>H2 Width: {{rect.width}}/p>
directives: []
export class App {
constructor(element: ElementRef) { = 'Angular2'
this.element = element;
this.ruler = new Ruler(new browser.BrowserDomAdapter());
this.rect = {};
  ngOnInit() {
var vm = this;
var measure = this.ruler.measure(this.element);
measure.then(function (rect) {
console.log('Rect', rect);
vm.rect = rect;

I hope you are enjoying with this post! Please share with you friends. Thank you!!

Share the post

ElementRef vs Renderer - Angular 2


Subscribe to Angular 2 Javascript C# Sql Server Knockoutjs Angularjs Kendo Ui Html 5 Web Api Wpf Wcf Etc.

Get updates delivered right to your inbox!

Thank you for your subscription