This post will show you how to access the DOM element in Angular 8-9.
Angular provides API to access DOM elements like ViewChild and elemetRef to access the DOM element in the component. It is straightforward to access the DOM element in a vanilla JavaScript
application. In Angular
, accessing the DOM element is not straightforward. In angular, you have to use Angular API like ViewChild
and elementRef
to access the DOM.
For this tutorial, I am using stackblitz
online cloud editor. Navigate to stackblitz and create a new application in stackbliz and then open the app.component.html and add the following code snippet
<input type="text" value="code Guru">
To access the input
element in the component, we need to create a template reference
variable in the HTML. To create a template reference variable in angular, add any name with the prefix #.
<input type="text" value="code Guru" #text>
Now to access this element in the component, we will use angular API ViewChild.
For this tutorial, I am going to access the input element and will set the focus
when the component load in the browser
What is ViewChild
ViewChild
provides the reference to the DOM or component declared in the template. To initialize or modify the element/component, we used the ngAfterViewInit
life cycle hook event.
Now open the app.component.ts file and import ViewChild
from the @angular/core
import {ViewChild} from '@angular/core'
The syntax for the ViewChild
decorator is:
@ViewChild([#template-reference ], {read: [reference type]});
read - Specify what kind of element you are trying to inject, like template reference, component, or directive
Static - True to resolve query results before change detection runs, false to resolve after change detection. Defaults to false.
import { Component, ViewChild, ElementRef, AfterViewInit } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements AfterViewInit {
@ViewChild("text", { read: ElementRef }) text: ElementRef;
ngAfterViewInit() {
console.log(this.text.nativeElement);
this.text.nativeElement.focus();
}
}
== DEMO==