Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between using angular 2 renderer and using nativeElement

Tags:

angular

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.

like image 471
Nima Hakimi Avatar asked Aug 08 '16 05:08

Nima Hakimi


People also ask

What are the difference between Renderer and ElementRef in Angular 2?

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.

When should I use Renderer 2?

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.

Why would you use Renderer methods instead of using native element methods in Angular?

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.

What is Angular render 2?

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.


1 Answers

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:

  • Angular2: ElementRef nativeElement vs querySelector performance
like image 90
Thierry Templier Avatar answered Nov 15 '22 09:11

Thierry Templier