Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Renderer2 in angular4? why it is preferred over jquery?

Tags:

angular

I want to understand what is and why Renderer2 is used in angular for DOM manipulation. Can we use the rich and famous library jQuery in place fo Renderer2 or native javascript? What is advantage of using Renederer2 over jQuery

like image 303
Mantu Nigam Avatar asked Dec 18 '17 04:12

Mantu Nigam


2 Answers

In a normal browser context Renderer2 is a simple default wrapper around DOM manipulation browser API. For example, here is the implementation of just a few of its methods:

class DefaultDomRenderer2 implements Renderer2 {

    addClass(el: any, name: string): void { el.classList.add(name); }

    createComment(value: string): any { return document.createComment(value); }

    createText(value: string): any { return document.createTextNode(value); }

    appendChild(parent: any, newChild: any): void { parent.appendChild(newChild); }

It's been introduced to abstract rendering operations away from pure DOM elements. For example, if you need to add a class you would do it like this:

constructor(el: ElementRef, renderer: Renderer2) {
    renderer.addClass(el.nativeElement, 'some');
}

Here you can see that you don't interact directly with native elements and don't use its API how you'd do it with jQuery:

constructor(el: ElementRef) {
    $(el.nativeElement).addClass('some');
}

The code with a renderer has a benefit of being able to run on platforms other than DOM if you provide different implementation of a renderer specific to that other platform. For example, Angular provides an implementation of Renderer2 for a webworker WebWorkerRenderer2. It implements the API methods like addClass using postMessage methods to communicate to the main application that DOM needs to be updated.

like image 93
Max Koretskyi Avatar answered Oct 17 '22 04:10

Max Koretskyi


Another solid example would be server-side rendering. If you are ever going to use server-side rendering then you should stay away from DOM as much as possible. Using renderer wrapper will allow you the safest way and multi-platform support for server-side rendering.

like image 40
hunterTR Avatar answered Oct 17 '22 04:10

hunterTR