getElementById Replacement in Angular

Rana Hasnain Khan Aug 31, 2023
  1. getElementById Replacement in Angular
  2. ElementRef in Angular
  3. Get Value From the Input Using ElementRef in Angular
  4. Angular Renderer2
  5. Conclusion: DOM Manipulation in Angular
getElementById Replacement in Angular

We will introduce the replacement of the getElementById function in Angular.

We will also introduce the ElementRef function in Angular to get the document’s element reference and value from the input.

getElementById Replacement in Angular

The getElementById method returns the element with the ID Attribute with the specified value. This method is most common in HTML DOM and is used almost every time we manipulate, get info from, or element in our document.

Because getElementById is a vanilla Javascript function and we use Typescript in Angular, the replacement to this function in Typescript are ElementRef and Renderer2 which we will introduce in this tutorial.

ElementRef in Angular

The ElementRef is a class that can wrap around a specified DOM element to enhance the methods and properties of a native element. If we define an element as an ElementRef, we can access it as a nativeElement object.

This article is compatible with Angular 4 to Angular 12.

Let’s use ElementRef Interface in a class with the @ViewChild decorator to get element reference.

First of all, we will edit our app.component.html template and add the following code to it.

# angular

<div #myNameElem></div>

<button (click)="getValue()">Get Value</button>

Output:

1st Example of ElementRef in angular

In the app.component.ts file, we will add the following.

#angular
import { Component, VERSION, ViewChild, ElementRef } from "@angular/core";
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})

export class AppComponent {
  name = "Angular " + VERSION.major;
  @ViewChild("myNameElem") myNameElem: ElementRef;
  getValue() {
    console.log(this.myNameElem);
    this.myNameElem.nativeElement.innerHTML = "I am changed by ElementRef & ViewChild";
  }
}

Output:

ElementRef In Angular

Get Value From the Input Using ElementRef in Angular

Now we will introduce how to get the value of an input using ElementRef in Angular.

First of all, we will edit our app.component.html template and add the following code to it.

# angular
<input type="text" name="name" #myNameElem />
<button (click)="getValue()">Get Value</button>
<button (click)="resetValue()">Reset</button>

Output:

second example of ElementRef in angular

Now, in the app.component.ts file, we will add the following:

#angular
import { Component, VERSION, ViewChild, ElementRef } from '@angular/core';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular ' + VERSION.major;
  @ViewChild('myNameElem') myNameElem: ElementRef;
  getValue() {
    console.log(this.myNameElem.nativeElement.value);
  }
  resetValue() {
    this.myNameElem.nativeElement.value = '';
  }
}

Output:

Example of ElementRef In Angular

Angular Renderer2

Before we plunge into the specifics of Renderer2, let’s underline the motivation behind its adoption. Angular’s essence lies in its component-driven architecture, advocating for cleaner and more structured development practices. As a result, we seek alternatives to direct DOM manipulation, and Renderer2 emerges as a key player in this transition.

Introducing Renderer2: A Platform-Agnostic Powerhouse

Angular’s Renderer2 introduces a paradigm shift in DOM manipulation. It offers a platform-agnostic approach, ensuring that our actions adhere harmoniously to Angular’s change detection mechanisms. By utilizing Renderer2, we bridge the gap between traditional DOM manipulation and Angular’s component ecosystem.

A Glimpse of Renderer2 in Action

Let’s explore how Renderer2 empowers us with safe and structured DOM manipulation through a practical example:

Imagine a scenario where you want to dynamically modify the styles of a specific element. Renderer2 provides an elegant and secure method to achieve this:

#angular
<div #styledDiv></div>
<button (click)="applyStyles()">Apply Styles</button>
angularCopy code#angular
import { Component, ViewChild, ElementRef, Renderer2 } from "@angular/core";
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})

export class AppComponent {
  @ViewChild("styledDiv") styledDiv: ElementRef;

  constructor(private renderer: Renderer2) {}

  applyStyles() {
    const div = this.styledDiv.nativeElement;
    this.renderer.setStyle(div, "background-color", "lightblue");
    this.renderer.setStyle(div, "border", "1px solid darkblue");
  }
}

Conclusion: DOM Manipulation in Angular

The journey from getElementById to ElementRef and Renderer2 signifies more than a mere replacement—it’s a paradigm shift.

By embracing Angular’s component-driven philosophy, we transcend traditional JavaScript DOM manipulation. The dynamic capabilities of ElementRef and the safeguarded DOM manipulation of Renderer2 propel us into an era where our code harmonizes seamlessly with Angular’s architecture.

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn

Related Article - Angular Function