ElementRef: Easy but unsafe way of DOM Manipulation
One of the common way of manipulating DOM is using ElementRef
.
For example, let’s see, how to use ElementRef
to change the color of an element by using the color directive.
|
|
In most common use cases of manipulating DOM is using directive and using the nativeElement
property. Here, you can see, we have set the color to green
. It will change the color of the element, where this directive will be applied. That’s cool!, but it is not safe as per Angular docs. See (ElementRef: Security Risk)
Security Risk
As per Angular docs, ElementRef
has direct access to DOM, and it makes your application more vulnerable to XSS attacks. Use this, when you have no option left to access the DOM element.
Also, direct DOM access creates tight coupling between your application and rendering layers which will make it impossible to separate the two and deploy your application into a web worker.
Renderer2: Safer way of DOM Manipulation
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. This is the recommended approach because it then makes it easier to develop apps that can be rendered in environments that donβt have DOM access, like on the server, in a web worker or on native mobile.
Let’s modify our above example now by using Renderer2 and make our app safer.
|
|
And everything will work as expected. You can read more about Renderer2
by clicking on below link.
Summary
So, in this blog, we see why shouldn’t we use ElementRef for DOM manipulation. Using Renderer2 is safer way of DOM manipulation than ElementRef.
Further Reading
Angular Material Table With Paging, Sorting And Filtering
ng-template, ng-container And ngTemplateOutlet In Angular
Learn About Observables, Observers And Operators of RxJS β Angular