Tutorial

Using Renderer2 in Angular

Updated on March 1, 2021
author

Alligator.io

Using Renderer2 in Angular

The Renderer2 class is an abstraction provided by Angular in the form of a service that allows to manipulate elements of your app without having to touch the DOM directly. This is the recommended approach because it then makes it easier to develop apps that can be rendered in environments that don’t have DOM access, like on the server, in a web worker or on native mobile.

Note that the original Renderer service has now been deprecated in favor of Renderer2

Basic Usage

You’ll often use Renderer2 in custom directives because of how Angular directives are the logical building block for modifying elements. Here’s a simple example that uses Renderer2’s addClass method to add the wild class to elements that have the directive:

go-wild.directive.ts
import { Directive, Renderer2, ElementRef, OnInit } from '@angular/core';

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

  ngOnInit() {
    this.renderer.addClass(this.el.nativeElement, 'wild');
  }
}

Notice how we also use ElementRef to get access to the underlining native element that our directive is attached-to.

And now, you can add the directive to elements in a template and the wild class will be added when rendered:

<h1 appGoWild>
  Hello World!
</h1>
<!-- <h1 class="wild">Hello World!</h1> -->

You can see that overall the use of Renderer2 is not more complicated than manipulating the DOM directly. Let’s now go over some of the most useful methods:

createElement / appendChild / createText

Create new DOM elements and append them inside other elements. In this example, we create a new div and we create a text node. We then place the text node inside our new div and finally our div is added to the element referenced by our directive:

constructor(private renderer: Renderer2, private el: ElementRef) {}

ngOnInit() {
  const div = this.renderer.createElement('div');
  const text = this.renderer.createText('Hello world!');

  this.renderer.appendChild(div, text);
  this.renderer.appendChild(this.el.nativeElement, div);
}

Our template, once rendered, will look like this, given that we applied the directive on an article element:

<article>
  <div>Hello world!</div>
</article>

setAttribute / removeAttribute

Use setAttribute or removeAttribute to do just that, set or remove an attribute:

constructor(private renderer: Renderer2, private el: ElementRef) {}

ngOnInit() {
  this.renderer.setAttribute(this.el.nativeElement, 'aria-hidden', 'true');
}

addClass / removeClass

To addClass you can do the following:

constructor(private renderer: Renderer2, private el: ElementRef) {}

ngOnInit() {
  this.renderer.addClass(this.el.nativeElement, 'wild');
}

We’ve covered addClass in our above example. As for removeClass, simply provide the element reference and the name of the class to remove:

constructor(private renderer: Renderer2, private el: ElementRef) {}

ngOnInit() {
  this.renderer.removeClass(this.el.nativeElement, 'wild');
}

setStyle / removeStyle

Use setStyle to add inline styles using Renderer2:

constructor(private renderer: Renderer2, private el: ElementRef) {}

ngOnInit() {
  this.renderer.setStyle(
    this.el.nativeElement,
    'border-left',
    '2px dashed olive'
  );
}

…and removeStyle to remove it:

constructor(private renderer: Renderer2, private el: ElementRef) {}

ngOnInit() {
  this.renderer.removeStyle(this.el.nativeElement, 'border-left');
}

setProperty

With the following example, you can set the alt property on an image element:

constructor(private renderer: Renderer2, private el: ElementRef) {}

ngOnInit() {
  this.renderer.setProperty(this.el.nativeElement, 'alt', 'Cute alligator');
}

…or set the value of an input field:

// ...

ngOnInit() {
  this.renderer.setProperty(this.el.nativeElement, 'value', 'Cute alligator');
}

😄 This concludes our overview. Refer to the API documentation for a full list of available methods.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Alligator.io

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.