Renderer2
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.
Basic Usage
You’ll often use Renderer2 in custom directives because of how Angular directives are the logical building block for modifying elements. Here’s a simple example that uses Renderer2’s addClass method to add the wild class to elements that have the directive:go-wild.directive.ts
And now, you can add the directive to elements in a template and the wild class will be added when rendered:
You can see that overall the use of Renderer2 is not more complicated than manipulating the DOM directly. Let’s now go over some of the most useful methods:
createElement/appendChild/createText
Create new DOM elements and append them inside other elements. In this example, we create a new div and we create a text node. We then place the text node inside our new div and finally our div is added to the element referenced by our directive:
Our template, once rendered, will look like this, given that we applied the directive on an article element:
setAttribute/removeAttribute
Use setAttribute or removeAttribute to do just that, set or remove an attribute:
addClass/removeClass
We’ve covered addClass in our above example. As for removeClass, simply provide the element reference and the name of the class to remove:
setStyle/removeStyle
Use setStyle to add inline styles using Renderer2:
…and removeStyle to remove it:
setProperty
With the following example, you can set the alt property on an image element:
…or set the value of an input field:
😄 This concludes our overview. Refer to the API documentation for a full list of available methods.
Last updated