Angular: Stop manipulating DOM with ElementRef!

Need to share this story with you! Recently, I discovered the power of Renderer in Angular (Renderer is deprecated, use Renderer2 instead, but in this article I will just write Renderer)


Manipulating the DOM is easy with Angular. We can access directly the element by using ElementRef provided by @angular/core.

If you manipulate it by using a directive (common use case), probably that most of you will use nativeElement directly like this:

It will correctly change the color of the element. 👌 A lot of tutorials demonstrate the use of nativeElement, but is this safe? Not really…

Why is it so important?

According to Angular docs ElementRef, we can read:

Use this API as the last resort when direct access to DOM is needed. Permitting direct access to the DOM can make your application more vulnerable to XSS attacks. Carefully review any use of ElementRef in your code. Use templating and data-binding provided by Angular instead. Alternatively you take a look at Rendererwhich provides API that can safely be used even when direct access to native elements is not supported.
Relying on 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.

Not cool… 😒 BUT! We have an alternative called Renderer.

Renderer to manipulate the DOM!

Let’s take a look at this:

A lot of methods are useful to help us manipulating the DOM. In our use case, we just need to change a CSS property, the color. According to the API, we just need to use setStyle like this:

And all works as expected! 👌 Renderer is pretty useful for common use cases, and also to do complex DOM manipulation.

If you need to target a specific element, maybe you will need to use ViewChild, ContentChild,… If so, see this article:

Conclusion: Stop using ElementRef and use now Renderer!

If you enjoyed the article, please ❤️ it!