by Sai gowtham

How to access the dom nodes in angular

In this tutorial, we are going to learn about accessing the dom nodes or HTML elements present inside the angular components.

ViewChild

Angular provides us a ViewChild decorator method which helps us to access the particular dom nodes in the components.

Let’s see an example.

app.component.html
  <div>
     <input placeholder="Name" #myname />     <button (click)="handleFocus()">Focus</button>
     <button (click)="resetName()">Reset name</button>
  </div>

Here we have added a reference #myname to the input element now inside our AppComponent typescript file we can access the input element by using myname.

app.component.ts
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {

  @ViewChild('myname') nameInput: ElementRef;
  handleFocus() {
    this.nameInput.nativeElement.focus();  }

  resetName() {
    this.nameInput.nativeElement.value = '';  }

}

In the above code, first, we have imported ViewChild decorator and ElementRef type from @angular/core package.ViewChild decorator method accepts a dom node as its first argument so that we passed myname which is the same name we defined inside app.component.html.

We have created two methods handleFocus and resetName which helps us to focus the input element and resetting the previous data.

angular-viewchild-example

Have you seen in the above image we are focussing the input element by clicking a Focus button and resetting the name by clicking a reset name button.

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 JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course