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


@Component({
  selector: 'my-app',
  providers: [ElementRef],
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <p>H2 Height: {{rect.height}}</p>
      <p>H2 Width: {{rect.width}}</p>
    </div>
  `,
  directives: []
})
export class App {
  constructor(element: ElementRef) {
    this.name = '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!!
ANIL SINGH

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Google Amazon and Flipkart Book Store!

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.
ASK Questions
SQL Server NodeJs TypeScript JavaScript Angular SQL Server My Book