How to Use Renderer2 in Angular 16 Application

Last Updated on by in Angular Tutorial
Renderer2 in Angular will be dealt with in this article. Without directly touching DOM, you will be able to manipulate the elements of your app in Angular with the help of the Renderer2 class.This class is an abstraction. This approach is highly recommended for various reasons.

Angular Renderer2 Example

Thanks to the Renderer2 service in Angular, you will be able to develop apps which can be rendered in various environments, even the ones that don’t have DOM access.

For instance, you don’t have DOM access in environments like native mobile, web worker or a server.

You should keep in mind that the Renderer2 has replaced the no-deprecated Renderer Service.

Setup Angular Project

To work with Reactive Forms in Angular we must have a basic project setup. Follow the process to setup the project.

ng new angular-reactive-forms
# ? Would you like to add Angular routing? = Yes
# ? Which stylesheet format would you like to use? = SCSS

Ge into the project’s folder.

cd angular-reactive-forms

Fix Angular TypeScript Issues

To resolve error:

Property ‘xxxName’ comes from an index signature, so it must be accessed with [‘xxxName’]

This setting makes sure profound consistency between accessing a field via the “dot” (obj.key) syntax, and “indexed” (obj["key"]) and the way which the property is declared in the type.

Without this flag, TypeScript will allow you to use the dot syntax to access fields which are not defined:

Make sure to set following properties in tsconfig.json file:

"compilerOptions": {
 ...
 ...
   "strict": false,
   "noPropertyAccessFromIndexSignature": false,
 ...
 ...
},
  "angularCompilerOptions": {
    "strictTemplates": false
  }

Fundamental Usage of Renderer2 in Angular

Let’s decode Renderer2 with a custom directive. Custom directives in Angular have much application for Renderer2.

As far as modifying elements are concerned, Angular directives are regarded as the logical building block. We are going to look at a simple example below. Here we use the addClass method of Renderer2.

Here we add the crazy class to elements with the help of custom directive.

Run the following command to generate custom directive in Angular app.

ng generate directive crazy

crazy.directive.ts

import { Directive, Renderer2, ElementRef, OnInit } from '@angular/core';
@Directive({
  selector: '[appCrazy]'
})
export class CrazyDirective implements OnInit {
  constructor(
    private renderer: Renderer2, 
    private elmRef: ElementRef
  ) { }
  ngOnInit() {
    this.renderer.addClass(this.elmRef.nativeElement, 'crazyClass')
  }
  
}

We also use ElementRef in order to gain access the native elements beneath it.

In a template, you will be able to attach the directive to elements. Moreover, when you render it, the wild class will be added.

<h1 appCrazy>
  Hello World
</h1>

You will notice that directly manipulating the DOM is more complicated than Renderer2. Now we are going to look at some of the most useful methods below:

Using createElement / createText / appendChild

We are going to create new DOM elements before we append them within other elements. We have come up with a <p> tag in this example.

Moreover, we have created a text node after that. After that we have placed the text node inside the newly created <p> tag with the help of Renderer2 service class in Angular:

content.directive.ts

import { Directive, Renderer2, ElementRef, OnInit } from '@angular/core';
@Directive({
   selector: '[createContent]'
})
export class ContentDirective implements OnInit {
   constructor(
      private renderer: Renderer2,
      private elmRef: ElementRef
   ) { }
   ngOnInit() {
      const p = this.renderer.createElement('p');
      const text = this.renderer.createText('I am dynamically created');
      this.renderer.appendChild(p, text);
      this.renderer.appendChild(this.elmRef.nativeElement, p);
   }
}

This is how our HTML template will look after we have applied custom directive:

<!-- Add directive -->
<div createContent></div>

setAttribute / removeAttribute with Renderer2 in Angular

In order to remove or set an attribute, we use removeAttribute or setAttribute:

set-attribute.directive.ts

import { Directive, Renderer2, ElementRef, OnInit } from '@angular/core';
@Directive({
   selector: '[setAttribute]'
})
export class AttributeDirective implements OnInit {
   constructor(
      private renderer: Renderer2,
      private elmRef: ElementRef
   ) { }
   ngOnInit() {
      this.renderer.setAttribute(this.elmRef.nativeElement, 'aria-hidden', 'true');
   }
}
<!-- Set attribute directive -->
<h2 setAttribute>Hello World</h2>

removeClass using Angular 16 Renderer2 Service

We have already explored the addClass method of Renderer2 in the previous example.

Have a look at the following example to learn more about removeClass. We have named the class to remove and provided the element reference:

remove-class.directive.ts

import { Directive, Renderer2, ElementRef, OnInit } from '@angular/core';
@Directive({
   selector: '[removeClass]'
})
export class removeDirective implements OnInit {
   constructor(
      private renderer: Renderer2,
      private elmRef: ElementRef
   ) { }
   ngOnInit() {
      this.renderer.removeClass(this.elmRef.nativeElement, 'crazyClass');
   }
}
<!-- Remove class -->
<h1 appCrazy removeClass>Hello World</h1>

setStyle and removeStyle using Renderer2 in Angular

In order to work with inline styles, we use setStyle in Renderer2:

import { Directive, Renderer2, ElementRef, OnInit } from '@angular/core';
@Directive({
   selector: '[setStyle]'
})
export class setStyleDirective implements OnInit {
   constructor(
      private renderer: Renderer2,
      private elmRef: ElementRef
   ) { }
   ngOnInit() {
      this.renderer.setStyle(
         this.elmRef.nativeElement,
         'background',
         'pink'
      );
   }
}
<!-- set inline style  -->
<div class="inlineStyle" setStyle></div>

…and in order to remove it, we use removeStyle:

constructor(
  private renderer: Renderer2, 
  private elmRef: ElementRef
) {}
 
ngOnInit() {
  this.renderer.removeStyle(this.elmRef.nativeElement, 'background');
}

setProperty using Renderer2

In the following example, we have shown how we can set the title property on the anchor tag:

set-prop.directive.ts

import { Directive, Renderer2, ElementRef, OnInit } from '@angular/core';
@Directive({
   selector: '[setProp]'
})
export class setPropDirective implements OnInit {
   constructor(
      private renderer: Renderer2,
      private elmRef: ElementRef
   ) { }
   ngOnInit() {
      this.renderer.setProperty(this.elmRef.nativeElement, 'title', 'Hey there');
   }
}
<!-- set property  -->
<a setProp>I've got dynamic title!</a>

Run the following command to start the app.

ng serve --open

Here we conclude the overview. To have a comprehensive idea about all the available methods, you may take a look at the Angular API documentation.

❤️ Checkout Popular CSS Collection

Digamber - Author positronX.io

Digamber, the founder of PositronX, is a certified web developer with over 10 years of experience. He possesses a curiosity for learning new things and enjoys playing cricket on his days off.