Like Javascript’s getElementById()
method, there is no similar method in Angular that you can directly use to get a DOM element.
This is because Angular doesn’t allow you to directly manipulate the DOM. Instead, it encourages you to use its template syntax and data binding to update the view based on your component’s state.
But what if you want direct access to a DOM element and do some manipulation on it? Worry not, Angular provides many ways to achieve this.
In this article, we will discuss the most commonly used approach to access a DOM element directly from the component file. So let’s get started.
Get the HTML DOM Element using @ViewChild() Decorator
In Angular, the @ViewChild()
decorator is used to gain access to a child component, directive, or DOM element.
To get a DOM element using the @ViewChild()
decorator, you have to first give the target element a template reference variable. A template reference variable starts with the # symbol followed by a name you provide to it, eg. #myInput, #para, etc.
Let’s say we want to access the inner text of a div element and set its background color to yellow as soon as the page loads.
To achieve this, we have to first give it a reference using a template reference variable.
<!-- Div element with a template reference variable --> <div #myDiv> This is my div element. </div>
Next, in the component file, import @ViewChild()
decorator from ‘@angular/core’ and pass the name of the template reference variable(without # symbol) to the @ViewChild()
decorator and create a variable of type ElementRef
to access the element.
Place all the code related to the DOM element inside the ngAfterViewInit()
lifecycle hook as it makes sure that the page has finished loading.
import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.css'] }) export class DashboardComponent implements OnInit, AfterViewInit { @ViewChild('myDiv') divElement!: ElementRef; constructor() { } ngOnInit(): void { } ngAfterViewInit() { // Get the DOM element let element = this.divElement.nativeElement; // Get the element's inner text console.log(element.innerText); // Set the element's background color to yellow element.style.backgroundColor = 'yellow'; // Set some padding element.style.padding = '30px'; } }
Here is the output of the above code:
You can use this approach to access any DOM element and manipulate its value.
However, directly manipulating the DOM is not recommended in Angular as it can impact the Angular’s change detection system.
Manipulating the DOM using rederer2
However, directly manipulating the DOM isn’t recommended in Angular as it can bypass Angular’s change detection mechanism and lead to unexpected behavior. But if you want it anyways, you must use the renderer2 service provided by Angular.
The Renderer2 class has a bunch of inbuilt methods that you can directly use to manipulate the DOM.
In our example, we will use the setStyle()
method of Renderer2 to change the background color of the div we discussed in the previous example.
Here is the updated code:
import { AfterViewInit, Component, ElementRef, OnInit, Renderer2, ViewChild } from '@angular/core'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.css'] }) export class DashboardComponent implements OnInit, AfterViewInit { @ViewChild('myDiv') divElement!: ElementRef; constructor( private renderer2: Renderer2 ) { } ngOnInit(): void { } ngAfterViewInit() { // Get the DOM element let element = this.divElement.nativeElement; // Get the element's inner text console.log(element.innerText); // Set the element's background color to yellow this.renderer2.setStyle(element, 'background-color', 'yellow'); // Set some padding this.renderer2.setStyle(element, 'padding', '30px'); } }
The output will be the same as in the previous example. But this approach is more efficient.
That’s all for this article. Thanks for reading!