Angular Get Element By Id Value Example

By Hardik Savani | October 19, 2020 | 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 and angular 11 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 : Angular


Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.

We are Recommending you: