Loading episodes…
0:00 0:00

Angular 10 Renderer2 in Services with RendererFactory2: Append Dynamic Div Example

00:00
BACK TO HOME

Angular 10 Renderer2 in Services with RendererFactory2: Append Dynamic Div Example

10xTeam September 06, 2020 2 min read

In this quick example, how to dynamically create a div, with an id and append it to the body element in an Angular 10 service. We’ll see how to use RendererFactory2 in services to create an instance of Renderer2.

In services, you can use RendererFactory2 to create a Renderer2 instance. For example:

import { Injectable, Renderer2, RendererFactory2 } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DOMService {
  private renderer: Renderer2;
  constructor (rendererFactory: RendererFactory2) {
    // Get an instance of Renderer2
    this.renderer = this.rendererFactory.createRenderer(null, null);
  }

  createDIV() {
    // Use Renderer2 to create the div element
    const div = this.renderer.createElement('div');
    // Set the id of the div
    this.renderer.setProperty(div, 'id', 'container');
    // Append the div to the body element
    this.renderer.appendChild(document.body, div);

    return div;
  }
}

Creates and initializes a custom renderer that implements the Renderer2 base class. RendererFactory2

If you try to inject Renderer2 directly in a service you will get the following error because it can be only injected in components or directives:

Unhandled Promise rejection: StaticInjectorError[Renderer2]: 
  StaticInjectorError[Renderer2]: 
    NullInjectorError: No provider for Renderer2! ; Zone: <root> ; Task: Promise.then ; Value: Error: StaticInjectorError[Renderer2]: 
  StaticInjectorError[Renderer2]: 
    NullInjectorError: No provider for Renderer2!

Join the 10xdev Community

Subscribe and get 8+ free PDFs that contain detailed roadmaps with recommended learning periods for each programming language or field, along with links to free resources such as books, YouTube tutorials, and courses with certificates.

Audio Interrupted

We lost the audio stream. Retry with shorter sentences?