by Sai gowtham

How to select an element in Angular component

Consider we have a input element like this in our angular html file.

<input placeholder="name"/>

To acess this above element data inside the component we can do it like this.

First add a #myname reference to the input element.

<input placeholder="name" #myname />

Now import ElementRef,ViewChild from the @angular/core and access the input element by using the reference.

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild('myname') input:ElementRef;

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

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
130,921 students enrolled
48.5 hours of video content
View Course