What is elementRef in Angular?

ElementRef

According to the official documentation, Angular ElementRef serves as a wrapper around a native element within a View. It provides a class that encapsulates native DOM elements in the browser, enabling seamless interaction with the DOM. By utilizing the nativeElement object, developers gain access to all the methods and properties of the native elements.

Let’s explore how to access DOM elements within an Angular component using ElementRef and leverage its capabilities for dynamic manipulation.

Consider the following Angular component, where we have a div element that we want to show based on certain conditions. While accessing DOM elements is straightforward in a regular JavaScript application, Angular requires the use of specific Angular APIs to interact with the DOM

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>

To access the DOM element in Angular, we utilize the ElementRef API.

  1. First, create a template reference variable in your component, in this case, #myDiv.
  2. Import ViewChild and declare a variable of type ElementRef in the TypeScript file.
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);
  }
}

Now, you have access to all the properties of the div element in your TypeScript file. The ViewChild decorator allows you to bind the #myDiv template reference variable to the elementView variable of type ElementRef. By using this variable, you can manipulate the div element dynamically.

The ngOnInit lifecycle hook sets the isShow property to true, which will trigger the div element to be displayed based on the *ngIf condition in the template. In the ngAfterViewInit hook, we log the elementView to the console, demonstrating the successful access to the DOM element.

By leveraging Angular ElementRef, developers can seamlessly work with the DOM elements within an Angular application, enabling dynamic manipulation and interactivity.

Conclusion:

Angular ElementRef simplifies the process of accessing and manipulating DOM elements within an Angular application. By following the steps outlined above, you can effectively work with the nativeElement object and leverage its properties and methods. Incorporating ElementRef empowers developers to create dynamic and interactive Angular applications with ease.

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

Post a Comment (0)
Previous Post Next Post