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.
source share