Angular Get Element By Id Value Example

By Hardik Savani May 2, 2024 Category : Angular

Hi All,

In this tute, we will discuss angular get element by id value. you can understand a concept of how to get value using id in angular. i explained simply step by step how to get value by id in angular. we will help you to give example of how to set value using id in angular. So, let's follow few step to create example of angular get input value by id.

In this article, i will show you how to get and set value by id in angular 7, angular 8, angular 9, angular 10, angular 11, angular 12, angular 13, angular 14, angular 15, angular 16 and angular 17 application.

Here, we will simply take one input text box field with two buttons call "get value" and "reset value". when you click on get value button then we will get value using ElementRef id and when you click on the reset button then we will set the value using ElementRef id.

So, let's see simple example and i hope it can help you.

src/app/app.component.ts

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 = "";

}

}

src/app/app.component.html

<input type="text" name="name" #myNameElem>

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

<button (click)="resetValue()">Reset</button>

Ouput:

You can see bellow layout:

I hope it can help you...

Tags :
Shares