Home  >  Angular

Angular 4 Renderer2 Example

By Arvind Rai, August 25, 2017
This page will walk through Angular 4 Renderer2 example. It is used for UI rendering manipulation. Using Renderer2, we can create element, provide a text and then it can be appended with any existing element at run time on any event of an element. We can add and remove CSS classes, styles, HTML attributes using Renderer2 to change the UI. We can also set DOM property with a value at run time using Renderer2. We can append and remove a child element within a parent element using Renderer2. It can also be used to add a HTML comment to a given parent element. We can also bind an element to listen event using Renderer2. Here on this page we will discuss methods of Renderer2 using Angular component and directive. Renderer2 can be used with ElementRef. Now find the complete example step by step.


Technologies Used

Find the technologies being used in our example.
1. Angular 4.2.4
2. TypeScript 2.3.3
3. Node.js 6.10.1
4. Angular CLI 1.3.1
5. Angular Compiler CLI 4.2.4

1. createElement(), createText(), appendChild()

Here we will provide example of createElement(), createText() and appendChild() methods of Renderer2 service.
createElement(): Creates element such as <div>, <ul>, <li> etc. These elements need to be appended with any existing element.
createElement(name: string, namespace?: string|null): any 
createText(): Creates text that needs to be appended with any existing element.
createText(value: string): any
appendChild(): Appends new element to any existing element.
appendChild(parent: any, newChild: any): void
Find the example of createElement(), createText(), appendChild() using component.
append-demo.component.ts
import { Component, ElementRef, Renderer2, ViewChild } from '@angular/core';

@Component({
   selector: 'app-append',
   templateUrl: './append-demo.component.html'
})
export class AppendDemoComponent { 
   @ViewChild('abcd') 
   private abcd: ElementRef;	
   constructor(private renderer: Renderer2) {
   }
   onClick() {
     const li = this.renderer.createElement('li');
     const text = this.renderer.createText('Click here to add li');
     this.renderer.appendChild(li, text);
     this.renderer.appendChild(this.abcd.nativeElement, li);
   }
} 
append-demo.component.html
<h3>createElement(), createText(), appendChild()</h3>
<ul (click) = "onClick()" #abcd>
  <li>Click here to add li</li>
</ul> 
Find the example using directive.
cp1.directive.ts
import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';

@Directive({ 
     selector: '[cp1]' 
})
export class CP1Directive {
   constructor(private elRef: ElementRef, private renderer: Renderer2) {
   }
   @HostListener('click') 
   performTask() {
     const li = this.renderer.createElement('li');
     const text = this.renderer.createText('Click here to add li');
     this.renderer.appendChild(li, text);
     this.renderer.appendChild(this.elRef.nativeElement, li);
   }
} 
Now use cp1 directive as given below.
<ul cp1>
  <li>Click here to add li</li>
</ul> 
Suppose we click one time. Now find the source code in DOM.
<ul _ngcontent-c1="" cp1="">
  <li _ngcontent-c1="">Click here to add li</li>
  <li _ngcontent-c1="">Click here to add li</li>
</ul>

2. insertBefore()

Method signature of insertBefore() of Renderer2 service is as follows.
insertBefore(parent: any, newChild: any, refChild: any): void 
It inserts a new element before an element and within a parent element.
cp2.directive.ts
import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';

@Directive({ 
     selector: '[cp2]' 
})
export class CP2Directive {
   constructor(private elRef: ElementRef, private renderer: Renderer2) {
   }
   @HostListener('click') 
   performTask() {
       const div = this.renderer.createElement('div');
       const text = this.renderer.createText('Hello World!');
       this.renderer.appendChild(div, text);
	 
       const parent = this.elRef.nativeElement.parentNode;
       const refChild = this.elRef.nativeElement;
       this.renderer.insertBefore(parent, div, refChild);
   }
}
Find the HTML code to use cp2 directive.
<div>
  <div cp2>Click</div>
</div> 
Suppose we click one time then we will get following source code in DOM.
<div _ngcontent-c1="">
   <div _ngcontent-c1="">Hello World!</div>
   <div _ngcontent-c1="" cp2="">Click</div>
</div> 

3. removeChild()

Method signature of removeChild() of Renderer2 service is as follows.
removeChild(parent: any, oldChild: any): void 
It removes a given element within a given parent.
cp3.directive.ts
import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';

@Directive({ 
     selector: '[cp3]' 
})
export class CP3Directive {
   constructor(private elRef: ElementRef, private renderer: Renderer2) {
   }
   div = this.renderer.createElement('div');
   text = this.renderer.createText('Namaste!!!!!');
   
   @HostListener('mouseover') 
   onMouseOver() {
       this.renderer.appendChild(this.div, this.text);  
       this.renderer.appendChild(this.elRef.nativeElement, this.div);
   }
   @HostListener('mouseleave') 
   onMouseLeave() {
       this.renderer.removeChild(this.elRef.nativeElement, this.div);
   }   
} 
Find the HTML code to use cp3 directive.
<div cp3>Mouse Over</div> 
On mouse over a <div> with some text will be added and on mouse leave that <div> will be removed.

4. selectRootElement()

Method signature of selectRootElement() of Renderer2 service is as follows.
selectRootElement(selectorOrNode: string|any): any 
It returns the element reference picked up by given element name or CSS class name. If we pass any element name or class name such as div then first element from top in DOM will be picked up.
cp4.directive.ts
import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';

@Directive({ 
     selector: '[cp4]' 
})
export class CP4Directive {
   constructor(private elRef: ElementRef, private renderer: Renderer2) {
   }
   @HostListener('click') 
   performTask() {
     //const element = this.renderer.selectRootElement('div'); 	 	   
     const element = this.renderer.selectRootElement('.myclass'); 
     const text = this.renderer.createText('Namaste!!!');
     this.renderer.appendChild(element, text);
   }
} 
Find the HTML code to use cp4 directive.
<div cp4>click</div>
<div class="myclass"></div> 
When we click then we get following source code in DOM.
<div _ngcontent-c1="" cp4="">click</div>
<div _ngcontent-c1="" class="myclass">Namaste!!!</div> 

5. setAttribute() and removeAttribute()

Here we will provide example of setAttribute() and removeAttribute() methods of Renderer2 service.
setAttribute(): Sets attribute and its value to an element.
setAttribute(el: any, name: string, value: string, namespace?: string|null): void 
removeAttribute(): Removes the attribute from the element.
removeAttribute(el: any, name: string, namespace?: string|null): void 
Now find the directive to use above methods.
cp5.directive.ts
import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';

@Directive({ 
     selector: '[cp5]' 
})
export class CP5Directive {
   constructor(private elRef: ElementRef, private renderer: Renderer2) {
   }
   @HostListener('mouseover') 
   onMouseOver() {
       this.renderer.setAttribute(this.elRef.nativeElement, 'value', 'Namaste!');
   }
   @HostListener('mouseleave') 
   onMouseLeave() {
       this.renderer.removeAttribute(this.elRef.nativeElement, 'value');
   }   
} 
Find the HTML code to use cp5 directive.
<input type="text" cp5/> 
On mouse over we will get following source code in DOM.
<input _ngcontent-c1="" cp5="" type="text" value="Namaste!"> 

6. setProperty()

Method signature of setProperty() of Renderer2 service is as follows.
setProperty(el: any, name: string, value: any): void 
It sets a property with a value to an element. The difference between attribute and property of a HTML element is that attributes are defined by HTML and properties are defined by DOM. Now find the directive to use setProperty() method.
cp6.directive.ts
import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';

@Directive({ 
     selector: '[cp6]' 
})
export class CP6Directive {
   constructor(private elRef: ElementRef, private renderer: Renderer2) {
   }
   @HostListener('click') 
   performTask() {
      this.renderer.setProperty(this.elRef.nativeElement, 'id', 'xyz');
   }
} 
Find the HTML code to use cp6 directive.
<div cp6>--- Click Here --- </div> 
When we click on DIV element then a property named as id will be added. Find its source code in DOM.
<div _ngcontent-c1="" cp6="" id="xyz">--- Click Here --- </div> 

7. addClass() and removeClass()

Here we will provide example of addClass() and removeClass() methods of Renderer2 service.
addClass(): Adds a CSS class to a given element.
addClass(el: any, name: string): void 
removeClass(): Removes the CSS class from given element.
removeClass(el: any, name: string): void 

Now find the directive to use above methods.
cp7.directive.ts
import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';

@Directive({ 
     selector: '[cp7]' 
})
export class CP7Directive {
   constructor(private elRef: ElementRef, private renderer: Renderer2) {
   }
   @HostListener('mouseover') 
   onMouseOver() {
       this.renderer.addClass(this.elRef.nativeElement, 'abc');
       //Add more class
       //this.renderer.addClass(this.elRef.nativeElement, 'efg');
   }
   @HostListener('mouseleave') 
   onMouseLeave() {
       this.renderer.removeClass(this.elRef.nativeElement, 'abc');
       //Remove more class
       //this.renderer.removeClass(this.elRef.nativeElement, 'efg');
   }   
} 
Find the HTML code to use cp7 directive.
<div cp7>--- Namaste! --- </div> 
On mouse over the CSS class will be added and on mouse leave CSS class will be removed. Find the source code of DOM on mouse over.
<div _ngcontent-c1="" cp7="" class="abc">--- Namaste! --- </div> 

8. setStyle() and removeStyle()

Here we will provide example of setStyle() and removeStyle() methods of Renderer2 service.
setStyle(): Sets a style to the given element.
setStyle(el: any, style: string, value: any, flags?: RendererStyleFlags2): void 
removeStyle(): Removes a style from the given element.
removeStyle(el: any, style: string, flags?: RendererStyleFlags2): void 
Now find the directive to use above methods.
cp8.directive.ts
import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';

@Directive({ 
     selector: '[cp8]' 
})
export class CP8Directive {
   constructor(private elRef: ElementRef, private renderer: Renderer2) {
   }
   toggleFlag = false;
   @HostListener('click') 
   performTask() {
	   this.toggleFlag = (this.toggleFlag === true)? false : true;
	   if(this.toggleFlag) {
		   this.renderer.setStyle(this.elRef.nativeElement, 'color', 'red');
		   this.renderer.setStyle(this.elRef.nativeElement, 'font-size', '20px');
	   } else {
		   this.renderer.removeStyle(this.elRef.nativeElement, 'color');
		   this.renderer.removeStyle(this.elRef.nativeElement, 'font-size');
	   }
   }
} 
Find the HTML code to use cp8 directive.
<div cp8> Toggle </div> 
On toggling, style will be added and removed. Find the source code of DOM when style is added.
<div _ngcontent-c1="" cp8="" style="color: red; font-size: 20px;"> Toggle </div> 

9. parentNode()

Method signature of parentNode() of Renderer2 service is as follows.
parentNode(node: any): any 
It fetches the parent node for the given element. We will create an example using directive in which we have a DIV and its two children DIV. On the click of a child DIV, we will add style to parent DIV.
cp9.directive.ts
import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';

@Directive({ 
     selector: '[cp9]' 
})
export class CP9Directive {
   constructor(private elRef: ElementRef, private renderer: Renderer2) {
   }
   @HostListener('click') 
   performTask() {
	   const parent = this.renderer.parentNode(this.elRef.nativeElement);
	   this.renderer.setStyle(parent, 'color', 'red');
   }
} 
Find the HTML code to use cp9 directive.
<div> 
  <div>Namaste!!</div>
  <div cp9> --- Click Here --- </div>
</div> 
When we click on child DIV, we will get following source code of DOM.
<div _ngcontent-c1="" style="color: red;"> 
  <div _ngcontent-c1="">Namaste!!</div>
  <div _ngcontent-c1="" cp9=""> --- Click Here --- </div>
</div> 

10. createComment()

Method signature of createComment() of Renderer2 service is as follows.
createComment(value: string): any 
It creates a HTML comment that can be appended with an element. Find the directive to use createComment() method.
cp10.directive.ts
import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';

@Directive({ 
     selector: '[cp10]' 
})
export class CP10Directive {
   constructor(private elRef: ElementRef, private renderer: Renderer2) {
   }
   @HostListener('click') 
   performTask() {
       const comment = this.renderer.createComment('Testing createComment()');
       this.renderer.appendChild(this.elRef.nativeElement, comment);
   }
} 
Find the HTML code to use cp10 directive.
<div cp10>
 --- Click Here --- 
</div> 
When we click we will get following source code of DOM.
<div _ngcontent-c1="" cp10="">
  --- Click Here --- 
 <!--Testing createComment()-->
</div> 

11. listen()

Method signature of listen() of Renderer2 service is as follows.
listen(target: 'window'|'document'|'body'|any, eventName: string, callback: (event: any) => boolean | void): () => void 
It listens the event of an element. Find the listen() example using component. Here we will bind click event with DIV element.
listen-demo.component.ts
import { Component, AfterViewInit, ElementRef, Renderer2, ViewChild } from '@angular/core';

@Component({
   selector: 'app-listen',
   templateUrl: './listen-demo.component.html',
   styles: ['.abc {color: red; font-size: 20px}']
})
export class ListenDemoComponent implements AfterViewInit { 
   @ViewChild('xyz') 
   private xyz: ElementRef;	
   constructor(private renderer: Renderer2) {
   }
   toggleFlag = false;   
   ngAfterViewInit() {
	this.renderer.listen(this.xyz.nativeElement, 'click', () => {
		   
	   this.toggleFlag = (this.toggleFlag === true)? false : true;
	   if(this.toggleFlag) {
	       this.renderer.setStyle(this.xyz.nativeElement, 'color', 'red');
	   } else {
	       this.renderer.removeStyle(this.xyz.nativeElement, 'color');
	   }
		   
	});
   }
} 
listen-demo.component.html
<h3>listen()</h3>
<div #xyz> --- Click Here --- </div> 
Now find the listen() example using directive.
cp11.directive.ts
import { Directive, ElementRef, HostListener, Renderer2, AfterViewInit } from '@angular/core';

@Directive({ 
     selector: '[cp11]' 
})
export class CP11Directive implements AfterViewInit {
   constructor(private elRef: ElementRef, private renderer: Renderer2) {
   }
   toggleFlag = false;   
   ngAfterViewInit() {
	this.renderer.listen(this.elRef.nativeElement, 'click', () => {
		   
	   this.toggleFlag = (this.toggleFlag === true)? false : true;
	   if(this.toggleFlag) {
	      this.renderer.setStyle(this.elRef.nativeElement, 'color', 'red');
	   } else {
	      this.renderer.removeStyle(this.elRef.nativeElement, 'color');
	   }
		   
	});
   }
} 
Find the HTML code to use cp11 directive.
<div cp11> --- Click Here --- </div> 
On toggling a style will be added and removed. Find the source code of DOM when style is added.
<div _ngcontent-c1="" cp11="" style="color: red;"> --- Click Here --- </div> 

Application Module, Component and HTML Template used in Demo

cp.component.html
<h3>createElement(), createText(), appendChild()</h3>
<ul cp1>
  <li>Click here to add li</li>
</ul>

<h3>insertBefore()</h3>
<div>
  <div cp2>Click</div>
</div>

<h3>removeChild()</h3>
<div cp3>Mouse Over</div>

<h3>selectRootElement()</h3>
<div cp4>click</div>
<div class="myclass"></div>

<h3>setAttribute() and removeAttribute()</h3>
<div>
 Mouse Over on Input Box<br/><br/>
 <input type="text" cp5/>
</div>

<h3>setProperty()</h3>
<div cp6>--- Click Here --- </div>

<br/>Note: Id will be added to div tag

<h3>addClass() and removeClass()</h3>
Mouse Over on below word<br/><br/>
<div cp7>--- Namaste! --- </div>

<h3>setStyle() and removeStyle()</h3>
<div cp8> Toggle </div>

<h3>parentNode()</h3>
<div> 
  <div>Namaste!!</div>
  <div cp9> --- Click Here --- </div>
</div>

<h3>createComment()</h3>
<div cp10> --- Click Here --- </div>

<h3>listen()</h3>
<div cp11> --- Click Here --- </div> 
app.component.ts
import { Component } from '@angular/core';

@Component({
   selector: 'app-root',
   template: `
      <h2>1. Examples using Component  </h2>
      <app-append> </app-append>
      <app-listen> </app-listen>
      <h2>2. Examples using Directive  </h2>
      <app-cp></app-cp>
   `
})
export class AppComponent { 
} 
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';
import { CPComponent }  from './cp.component';
import { ListenDemoComponent } from './listen-demo.component';
import { AppendDemoComponent } from './append-demo.component';
import { CP1Directive }  from './cp1.directive';
import { CP2Directive }  from './cp2.directive';
import { CP3Directive }  from './cp3.directive';
import { CP4Directive }  from './cp4.directive';
import { CP5Directive }  from './cp5.directive';
import { CP6Directive }  from './cp6.directive';
import { CP7Directive }  from './cp7.directive';
import { CP8Directive }  from './cp8.directive';
import { CP9Directive }  from './cp9.directive';
import { CP10Directive }  from './cp10.directive';
import { CP11Directive }  from './cp11.directive';

@NgModule({
  imports: [     
        BrowserModule
  ],
  declarations: [
        AppComponent,
	CPComponent,
	ListenDemoComponent,
	AppendDemoComponent,
	CP1Directive,
	CP2Directive,
	CP3Directive,
	CP4Directive,
	CP5Directive,
	CP6Directive,
	CP7Directive,
	CP8Directive,
	CP9Directive,
	CP10Directive,
        CP11Directive		
  ],
  bootstrap: [
        AppComponent
  ]
})
export class AppModule { } 

Run Demo Application

To run the demo application, find following steps.
1. Download source code using download link given below on this page.
2. Use downloaded src in your angular CLI application. To install angular CLI, find the link.
3. Run ng serve using command prompt.
4. Now access the URL http://localhost:4200
Find the print screen.
Angular 4 Renderer2 Example

Reference

Renderer2

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us