Renderer2 Example: Manipulating DOM in Angular

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. We can also add or remove styles, HTML attributes, CSS Classes & properties, etc. We can also attach and listen to events etc.

Why not ElementRef?

We can use the nativeElement property of the ElelemtRef to manipulate the DOM. We learned this in our last tutorial on ElementRef. The nativeElement Property contains the reference to the underlying DOM object. This gives us direct access to the DOM, bypassing the Angular. There is nothing wrong with using it, but it is not advisable for the following reasons.

  1. Angular keeps the Component & the view in Sync using Templates, data binding & change detection, etc. All of them are bypassed when we update the DOM Directly.
  2. DOM Manipulation works only in Browser. You will not able to use the App in other platforms like in a web worker, in Server (Server-side rendering), or in a Desktop, or in the mobile app, etc where there is no browser.
  3. The DOM APIs do not sanitize the data. Hence it is possible to inject a script, thereby, opening our app an easy target for the XSS injection attack.

Using Renderer2

First import it from the @angular/core

inject it into the component

Use ElementRef & ViewChild to get the reference to the DOM element, which you want to manipulate.

Use the methods like setProperty , setStyle etc to change the property, styles of the element as shown below.

Code Example

Setting & Removing Styles (setStyle & removeStyle)

Use the setStyle & RemoveStyle to add or remove the styles. It accepts four argument.

The first argument is the element to which we want to apply the style. name of the styles is the second argument. The value of the style is the third argument. The last argument is Flags for style variations

Example

Use the last option RendererStyleFlags2 to add the !important or to make use of DashCase

Adding / Removing CSS Classes (addClass & removeClass)

Use the methods addClass / removeClass to add or remove classes.

Syntax

Example

Setting or Remove Attributes (setAttribute & removeAttribute)

We can add remove attributes using the setAttribute & removeAttribute

Example

Setting Property (setProperty)

Set any property of a DOM element using the setProperty method.

AppendChild

Use the appendChild to append a new element (child element) to any existing element (parent element).

It accepts two arguments. The first argument is the parent node, where we want to append a new child node. The second argument is the child node, which you want to add.

The next two examples, shows how to use appendChild.

Insert Text Element (CreateText & appendChild)

CreateText allow us to add text to the DOM.

Example

The following template has a empty div ( #divCreateText)

Use the ViewChild to inject the reference to the divCreateText in the component.

Use the createText method the create text node. At this point it is not added to the DOM.

Use the appendChild method to add it to an existing element (divCreateText).

Creating new Element (createElement & appendChild)

We can easily create a new element using the createElement & appendChild.

createElement creates a new element, but does not insert it into the DOM. To insert into the DOM, we need to add it to an element, which already exists in the DOM using appendChild method.

The following example shows how to create a new element and append to the DOM.

First, we inject ElementRef in the constructor. This will inject the DOM element hosting the component/directive.

Create a new div element using the method createElement('div'). It is not yet added to the DOM.

Make use of the createText('Inserted at bottom') to create a new text node.

Use appendChild to append the newly created text node to the div element. Note that div is not yet added to the DOM.

Finally, we add the div element to an existing DOM element i.e. host element.

The complete code as under. The createElement2 appends the new child node a another div.

InsertBefore

We can also insert the new element, before an element in the DOM element using the insertBefore method. The syntax of insertBefore as shown below.

parent is the parent node. newChild is the new node, which you want to insert. refChild is the existing child node before which newChild is inserted.

The following Example inserts a new element before div1.

First, use the ViewChild to get the reference to the div1. Inject ElementRef, which gives us the reference to the Host DOM element.

Create a new div element using createElement. Add a text node to it using createText and append it to the div

Use the insertBefore method to add the div element

Insert Comment

createComment creates comment node. It accepts comment as the argument. You can then use the appendChild or insertBefore to insert it anywhere in the DOM.

ParentNode & NextSibling

ParentNode method returns the parent of a given node in the host element’s DOM.

nextSibling method returns the next sibling node of a given node in the host element’s DOM.

SelectRootElement

We can also use the selectRoomElement to select a node element based on a selector.

Syntax

The first argument is the selector or node. The Renderer2 uses the selector to search for the DOM element and returns it.

The second argument is preserveContent. If no or undefined, the renderer2 will remove all the child nodes. If yes the child nodes are not removed.

Example, consider the following template

The selectRootElement in the following example returns the element div1 , but it removes all the content it holds. Because the second argument is false. Change false to true, then the renderer2 will not remove the content.

Examples.

Listen to DOM events

You can also, listen to DOM events using the listen method.

The listen method accepts three arguments. the first argument is the DOM element (target). The second argument is the name of the event (eventName) and the third argument is the callback

In the following example, we listen to the click event of a button.

Do not forget to unsubscribe to the this.clicklistener.unsubscribe()

Reference

  1. Renderer2

3 thoughts on “Renderer2 Example: Manipulating DOM in Angular”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top