I wanted to know what is difference between this code:
export class SomeDirective implements OnInit {
constructor(private _elRef: ElementRef){}
ngOnInit(): any {
this._elRef.nativeElement.style.backgroundColor = 'green';
}
}
and this one:
export class SomeDirective implements OnInit {
constructor(private _elRef: ElementRef, private _renderer: Renderer){}
ngOnInit(): any {
this._renderer.setElementStyle(this._elRef, 'background-color', 'green');
}
}
I know that the second one has some advantages over the first one, I just need to know what those advantages specifically are.
The Renderer is a class that is a partial abstraction over the DOM. Using the Renderer for manipulating the DOM doesn't break server-side rendering or Web Workers (where direct access to the DOM would break). ElementRef is a class that can hold a reference to a DOM element.
The Renderer2 allows us to manipulate the DOM elements, without accessing the DOM directly. It provides a layer of abstraction between the DOM element and the component code. Using Renderer2 we can create an element, add a text node to it, append child element using the appendchild method., etc.
Permitting direct access to the DOM can make your application more vulnerable to XSS attacks. Alternatively, you take a look at Renderer which provides API that can safely be used even when direct access to native elements is not supported.
The Renderer2 class is an abstraction provided by Angular in the form of a service that allows to manipulate elements of your app without having to touch the DOM directly.
My understanding is that Renderer
is an abstraction in Angular2. This means that a dedicated implementation is plugged behind according to the execution context. For example, in the browser, with web workers, from server side...
As a matter of fact, there are contexts when the DOM API isn't available. I think about web worker and server execution.
See this question:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With