According to the official docs. Angular ElementRef is a wrapper around a native element inside of a View. It’s simply a class that wraps native DOM elements in the browser and allows you to work with the DOM by providing the nativeElement object, which exposes all the methods and properties of the native elements.{alertInfo}
Let’s consider the following angular
component. The component has one div, and we want to show the div based on some conditions. In a normal javascript application, you can easily access the DOM element, but you have to use some angular API to access the DOM element in Angular.
app.component.html
<hello name="{{ name }}"></hello>
<p>
Start editing to see some magic happen :)
</p>
<div width="560" height="249" #myDiv *ngIf="isShow">
Code Guru
</div>
The API that we used to access the DOM element in angular is elementRef
.
First, create a template reference variable in your component (in our case, it is #myDiv) and then import ViewChild
and declare a variable in a typescript file as shown below.
@ViewChild('myDiv') elementView: ElementRef;
Now you can access all the properties of the div element in your typescript file.$ads={1}
import {
Component,
AfterViewInit,
ElementRef,
ViewChild,
OnInit
} from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit, OnInit {
name = 'Angular';
isShow = false;
@ViewChild('myDiv') elementView: ElementRef;
ngOnInit() {
this.isShow = true;
}
ngAfterViewInit() {
console.log(this.elementView);
}
}