DEV Community

Manthan Ankolekar
Manthan Ankolekar

Posted on

What is Renderer2? How to use it in Angular Project?

Renderer2 is a utility class that provides methods to manipulate and interact with the DOM (Document Object Model). It is used to perform operations such as creating, modifying, and removing elements, applying styles, and listening to events.

Here's an example of how you can use Renderer2 in Angular:

  1. Import the necessary modules and services:

    import { Component, Renderer2, ElementRef } from '@angular/core';
    
  2. Inject the Renderer2 and ElementRef into your component's constructor:

    constructor(private renderer: Renderer2, private el: ElementRef) { }
    
  3. Use the Renderer2 methods to manipulate the DOM in your component's methods or lifecycle hooks. For example, let's say you have a button in your template and you want to change its background color when it is clicked:

    @Component({
      selector: 'app-example',
      template: `
        <button (click)="changeColor()">Change Color</button>
      `
    })
    export class ExampleComponent {
      changeColor() {
        const button = this.el.nativeElement.querySelector('button');
        this.renderer.setStyle(button, 'background-color', 'red');
      }
    }
    

In the above example changeColor() method, we use this.el.nativeElement.querySelector('button') to get a reference to the button element in the DOM. Then, we use this.renderer.setStyle() to set the background color of the button to red.

Note that using Renderer2 is recommended when you need to manipulate the DOM directly in Angular, as it provides a safer way to interact with the DOM compared to directly accessing and modifying the DOM elements using vanilla JavaScript.

Top comments (0)