python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
angular 2 elementref vs. renderer

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!!

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - and
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like Powered by Blogger.
ASK Questions