What is Renderer2 in Corner4? why is this preferable to jquery?

I want to understand what is and why Renderer2 is used in angular to manipulate the DOM. Can we use the rich and famous jQuery library instead of Renderer2 or our own javascript? What is the advantage of using Renederer2 over jQuery

+5
source share
1 answer

In the normal browser context, Renderer2 is a simple default wrapper around the DOM browser API. For example, here is an implementation of only 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 was introduced for abstract rendering operations 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 are not interacting directly with your own elements and are not using its API, as you will do with jQuery:

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

Code with a renderer has the advantage that it can run on platforms other than the DOM if you provide a different rendering implementation specific to that other platform. For example, Angular provides a Renderer2 implementation for the WebWorkerRenderer2 web user. It implements API methods such as addClass , using postMessage methods to communicate with the main application that needs to update the DOM.

+6
source

Source: https://habr.com/ru/post/1274137/


All Articles