Today, I am going to write on a small but important topic of DOM manipulation. DOM manipulation is much easier in all versions of Angular 2+. Angular abstract the DOM and gives you the shallow copy to mess around it. It becomes more interesting with TypeScript because your editor can hint most of the DOM property method for you.
ElementRef: Easy but unsafe way of DOM Manipulation
One of the common way of manipulating DOM is using
ElementRef is a wrapper around a native element inside of a view.
For example, let’s see, how to
In most common use cases of manipulating DOM is using directive and using
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)
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
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.
So, in this blog, we see why shouldn’t we use ElementRef for DOM manipulation. Using Renderer2 is