JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > Angular >

Use TypeScript's getElementById replacement in Angular

Author:JIYIK Last Updated:2025/04/18 Views:

This tutorial guide provides a brief description of replacing AngularJS with TypeScript document.getElementById.

This also provides getElementByIdthe best practices for using in Angular with code examples. We will also see the use of DOM querySelector in TypeScript.

First, let's understand document.getElementByIdthe method in TypeScript and why it is popular among the developer community.


document.getElementById()Methods in TypeScript

document.getElementById()is a predefined JavaScript (and TypeScript) method that can be used to operate documenton the object. It returns an element with the specified value, or nothing if the element does not exist null.

document.getElementById()Is one of the most common and popular methods for working with HTML DOM in the developer community.

An important point to remember is that if two or more elements have the same id, document.getElementById()the first element will be returned.

Now, let's look at some coding examples to better understand their purpose and usage.

Consider a tag with some demotext having a unique id h1. Now, in scriptsthe section, if we want to target a particular tag, we use the method documentavailable in the object getElementById().

<!DOCTYPE html>
<html>
<body>

<h1 id="demo">The Document Object</h1>
<h2>The getElementById() Method</h2>
<script>
    document.getElementById("demo").style.color = "red";
</script>

</body>
</html>

Output:

Use getElementById to locate the output of the tag

Now let's consider a more dynamic example: an input field that accepts a number and returns its cubed value.

<!DOCTYPE html>
<html>
<body>

<form>
    Enter No:<input type="text" id="number" name="number"/><br/>
    <input type="button" value="cube" onclick="getcube()"/>
</form>

<script>
    function getcube(){
        var number=document.getElementById("number").value;
        alert(number*number*number);
    }
</script>

</body>
</html>

Output:

Use getElementById to get the output of the number

Now, let's look at the replacement in Angular using TypeScript getElementById.


Using TypeScript in Angular Use ElementRefas getElementByIda replacement

AngularJs's ElementRefis a wrapper around the HTML element that contains the attributes nativeElementand holds a reference to the underlying DOM object. Using ElementRef, we can manipulate the DOM in AngularJs using TypeScript.

By using ViewChild, we can get the HTML element's in the component class ElementRef. Angular allows injecting directive elements when a component's directive is requested in the constructor ElementRef.

Using @ViewChildthe decorator, we use the interface in the class ElementRefto get the element reference.

Consider the following code example from main.component.htmla .js file AngularJs. We have a button with an event and a myNamediv with a unique ID:

# angular

<div #myName></div>

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

Output:

HTML button to get value

Example 1 ( app.component.ts):

#angular
import { Component, VERSION, ViewChild, ElementRef } from "@angular/core";

@Component({
    selector: "my-app",
    templateUrl: "./main.component.html",
    styleUrls: ["./app.component.css"]
})

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

Output:

Output uses ElementRef to get a reference to the input

Using @ViewChildthe decorator, we get a reference to the input with the help of the interface in the class ElementRef. Then, we change its value using getData()the function with this reference.

Example 2 ( app.component.ts):

import { Component, ViewChild, ElementRef, AfterViewInit } from "@angular/core";

@Component({
    selector: "my-app",
    templateUrl: "./app.component.html",
    styleUrls: ["./app.component.css"]
})
export class AppComponent implements AfterViewInit {
    name = "Angular";

    @ViewChild("ipt", { static: true }) input: ElementRef;

    ngAfterViewInit() {
        console.log(this.input.nativeElement.value);
    }

    onClick() {
        this.input.nativeElement.value = "test!";
    }
}

Output:

Use ElementRef output to get a reference to the input and change the text

This will get a reference to the input field and change its inner text when the button is clicked.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Enabling HTML5 mode in AngularJS

Publish Date:2025/04/18 Views:148 Category:Angular

This article will guide you through enabling HTML5 mode with deep linking on your AngularJS application. Using HTML5 mode in AngularJS $locationProvider.html5Mode pushState is a way to tell the browser that it needs to use HTML5 mode for UR

Loading spinner in AngularJs

Publish Date:2025/04/18 Views:133 Category:Angular

We will cover how to add a loading spinner while the request is loading and stop the loader while data is loading in AngularJs. Loading spinner in AngularJs Loaders are a part of web applications to make them user-friendly and improve the u

Showing and hiding in Angular

Publish Date:2025/04/18 Views:91 Category:Angular

We will walk through examples of showing and hiding components or elements in Angular. Showing and hiding in Angular While developing business applications we need to hide some data based on user roles or conditions. We have to display the

Downloading files in Angular

Publish Date:2025/04/18 Views:164 Category:Angular

We will look at how to download a file in Angular by clicking a button and show an example. File downloading in Angular Downloading files in Angular is very easy. We can use HTML5 download attributes to download files. # angular a href = "F

Drag and drop in Angular

Publish Date:2025/04/18 Views:187 Category:Angular

We will introduce @angular/cdk/drag-drop the module to accomplish drag and drop in angular. We will also walk through some examples of drag and drop in Angular. Drag and drop in Angular @angular/cdk/drag-drop The module provides you with a

Select an option in the Angular drop-down menu

Publish Date:2025/04/18 Views:112 Category:Angular

We will cover how to set the selected option in an Angular dropdown, set the selected option from an array of options, and set the selected option if the options are dynamic in Angular. Setting the selected option in an Angular dropdown men

在 Angular 中上传文件

Publish Date:2023/04/14 Views:123 Category:Angular

本教程演示了如何在 Angular 中上传任何文件。我们还将介绍如何在文件上传时显示进度条,并在上传完成时显示文件上传完成消息。

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial