Renderer2 In Angular

Renderer2

Renderer2 is a class in Angular which is used for UI manipulation and rendering. Custom Rendering is done using this class. Using this class we can many manipulations in UI. We can create an element, add text nodes, etc. CSS classes are added and removed using Renderer2 methods. Even we can add elements to a parent element. Event binding can also be done using a listen() method. We can use this in making custom directives as well. We will use ElementRef to refer the element with Renderer2. 

Methods in Renderer2 Service

Now we will implement different methods of Renderer2 service one by one. We will see what a particular method does and the syntax for the same.

createElement(), createText(), appendChild() and createComment() Example

  • createElement() - This method is used to create different elements such as <div>, <span>, <li>, <img>, <input>, etc. We need to append these newly created elements to the existing ones.
    createElement(name: string, namespace?: string): any
    
    
  • createText() - This method is used to create text nodes which need to be appended with some HTML element.
    createText(value: string): any
    
    
  • appendChild() - This element is used to append newly created element to the existing element.
    
    appendChild(parent: any, newChild: any): void
    
    
  • createComment() - It creates an HTML comment which needs to be appended to some existing element.
    createComment(value:string): any
    

Example: Suppose we have a <div> and on click of this div a list should appear in the DOM. So we will see how this is done using the above methods. We will go to component.html file and write the below code for
element.

<div (click)="onDivClick()" #main>
</div> 

Now we will see how we will use Renderer2 and ElementRef to add a list.

import { Component, ElementRef, Renderer2, ViewChild } from '@angular/core';

@Component({
   selector: 'app-element-demo',
   templateUrl: './element-demo.component.html'
})
export class ElementDemoComponent { 
   @ViewChild('main') main: ElementRef;	
   constructor(private renderer: Renderer2) {
   }
   onDivClick() {
     const ul = this.renderer.createElement('ul');
     const li = this.renderer.createElement('li');
     const listText = this.renderer.createText('The first list item');
     this.renderer.appendChild(li,listText);
     this.renderer.appendChild(ul,li);
     this.renderer.appendChild(this.main.nativeElement, ul);
   }
} 

Custom Directives Using Renderer2

We will use custom directives to modify elements. Now we will use @Directive for creating custom directives. If we add ag1 in any element, an HTML comment will be added for that element. Use ElementRef to get access to the underlying element to which our directive is attached. We should have a <div ag1>Hello World</div>.

import { Directive, Renderer2, ElementRef, OnInit } from '@angular/core';

@Directive({
  selector: '[ag1]'
})
export class ag1Directive implements OnInit {
  constructor(private renderer: Renderer2, private el: ElementRef) {}

  ngOnInit() {
     const comment = this.renderer.createComment("Directive Renderer Example");
     this.renderer.appendChild(this.el.nativeElement, comment);
  }
}

setAttribute(), removeAttribute() Example

  • setAttribute() - This method set attribute with its value.
    
    setAttribute(el: any, name: string, value: string, namespace?: string): void
    
    
  • removeAttribute() - This method removes the attribute.
    removeAttribute(el: any, name: string, namespace?: string): void
    
Let us add alt attribute in the  <img> tag. On click we will add the attribute, on mouseleave we will remove the same attribute. We will add the event listeners using @HostListener decorator which attaches events to the host element. Suppose we have a <img ag11 src="#"/>

import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';

@Directive({ 
     selector: '[ag11]' 
})
export class ag11Directive {
   constructor(private el: ElementRef, private renderer: Renderer2) {
   }
   @HostListener('click') 
   onClick() {
       this.renderer.setAttribute(this.el.nativeElement, 'alt', 'Some alt text');
   }
   @HostListener('mouseover') 
   onDoubleClick() {
       this.renderer.removeAttribute(this.elRef.nativeElement, 'alt');
   }   
} 

Comments