Author -  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.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY