What is elementRef in Angular?

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.


<hello name="{{ name }}"></hello>
  Start editing to see some magic happen :)
<div width="560" height="249" #myDiv *ngIf="isShow">
  Code Guru

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 {
} from '@angular/core';

  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() {

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post