Angular
  • Angular learning
  • Angular
    • Change Detection
      • Angular Change Detection Strategies
      • Understanding Change Detection Strategy in Angular
    • Angular Components Overview
      • Lifecycle hooks
      • View encapsulation
    • Text interpolation
    • Pipes
    • ARIA
    • Event binding
    • Directives
    • Dependency injection in Angular
    • Difference between Template-Driven and Reactive Forms
    • Guards
    • Resolvers
      • Resolver example
  • Memory management in Angular applications
  • Renderer2
  • Angular test
    • Testing
      • The different types of tests
      • Some testing best practices
      • Angular Service Testing in Depth
        • About Jasmine
        • Jasmine - Test suites
        • Implementation of First Jasmine Specfication
        • spyOn() & jasmine.createSpyObj()
        • beforeEach()
        • Testing services
        • Disabled and Focused Tests
        • flush
        • HttpTestingController
        • Sample code
      • Angular Component Testing in Depth
        • Intro to Angular Component testing
        • DOM interaction
        • Trigger Change Detection
        • Test Card List Test Suite Conclusion
        • Window.requestAnimationFrame()
        • Asynchronous Work (Jasmine)
        • Cooperative asynchronous JavaScript: Timeouts and intervals
        • FakeAsync - Asynchronous Work (Jasmine) part 2
        • tick()
        • Sample codes
      • Testing Promised-based code-intro Microtasks
        • Microtasks
        • Micro-tasks within an event loop (Summary)
        • Macro-tasks within an event loop (Summary)
        • Test promised Microtasks (code)
      • Using fakeAsync to test Async Observables
      • Cypress.io
        • Create our first e2e test
      • Angular CLI code coverage and deployment in prod mode.
      • Travis CI
  • Angular best practices
    • Angular best practices
      • Security
      • Accessibility in Angular
      • Keeping your Angular projects up-to-date
    • Bootstrapping an Angular Application
      • Understanding the File Structure
      • Bootstrapping Providers
    • Components in Angular
      • Creating Components
      • Application Structure with Components
        • Accessing Child Components from Template
        • Using Two-Way Data Binding
        • Responding to Component Events
        • Passing Data into a Component
      • Projection
      • Structuring Applications with Components
      • Using Other Components
  • Reactive extensions
    • RxJS
      • RxJS Operators
      • of
      • Observable
      • async pipe (Angular)
      • Interval
      • fromEvent
      • Pipe
      • Map
      • Tap
      • ShareReplay
      • Concat
      • ConcatMap
      • Merge
      • MergeMap
      • ExhaustMap
      • fromEvent
      • DebounceTime
        • Type Ahead
      • Distinct Until Changed
      • SwitchMap
      • CatchError
      • Finalize
      • RetryWhen
      • DelayWhen
      • ForkJoin
      • First
      • Interview Questions
      • Zip
  • NgRx
    • What's NgRx
      • Actions
      • Reducers
      • Selectors
      • 🙅‍♂️Authentication guard with NgRX
      • @ngrx/effects
        • Side-Effect refresh survivor
  • Interview Q&A
    • Angular Unit Testing Interview Questions
    • Angular Questions And Answers
  • Angular Advanced
    • Setting up our environment
      • Understanding Accessors (TS)
      • The host & ::ng-deep Pseudo Selector
Powered by GitBook
On this page
  • Basic Usage
  • createElement/appendChild/createText
  • setAttribute/removeAttribute
  • addClass/removeClass
  • setStyle/removeStyle
  • setProperty

Was this helpful?

Renderer2

PreviousMemory management in Angular applicationsNextTesting

Last updated 4 years ago

Was this helpful?

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.

Basic Usage

You’ll often use Renderer2 in 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) {}

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

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 for a full list of available methods.

custom directives
API documentation