How to get and set value by id in Angular?

October 22, 2020 | Category : Other

Hi All,Here, i will show you how to set value using id in angular. This post will give you simple example of angular get input value by id. Here you will learn document getelementbyid set value angular. let’s discuss about angular get element by id value. Here, Creating a basic example of how to get value using id in angular.

In this article, i will show you how to get and set value by id in angular 7, angular 8, angular 9 and angular 10 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...