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