Blog>
Snippets

Creating and Appending Elements

Demonstrate how to create a new div element and append it to the body using Renderer2.
import { Renderer2, ElementRef } from '@angular/core';

// Assume constructor injection of renderer
constructor(private renderer: Renderer2) {}

// Function to create and append a div
createAndAppendDiv() {
  // Create a new div element
  const newDiv = this.renderer.createElement('div');

  // Optionally set attributes, classes, or styles
  this.renderer.setAttribute(newDiv, 'id', 'newDiv');
  this.renderer.addClass(newDiv, 'my-div-class');
  this.renderer.setStyle(newDiv, 'color', 'blue');

  // Append the new div to the body
  this.renderer.appendChild(document.body, newDiv);
}
This code snippet demonstrates how to create a new 'div' element with some attributes, styles, and classes using Renderer2, and how to append it to the body of the document. Renderer2 provides an API that allows you to create and manage DOM elements in a way that's compatible with Angular's view encapsulation and change detection mechanisms.