ElementRef In Angular

ElementRef In Angular

In this article, we will learn how to use ElementRef to get the reference of a HtmlElement and alter the DOM in Angular Applications. ElementRef in Angular is a wrapper around a native DOM element (HTML element). It has the nativeElement attribute, which is a reference to the underlying DOM object. It's possible to manipulate the DOM with it. To access the ElementRef of an HTML element in the component class, we use the ViewChild. When you request ElementRef of the Host element of the component or directive in the constructor, Angular also injects it.

ElementRef

The Browser creates and maintains the DOM objects. They represent the document's structure and content. We use these DOM objects to alter the View in Vanilla JavaScript code. We can create and change documents, as well as browse their structure and add, modify, and delete parts and information.

To alter the DOM, Angular provides a variety of tools and strategies. Components can be added or removed. It includes a number of directives, such as the Class Directive and the Style Directive, that allow users to manipulate their styles, among other things.

On rare occasions, we may need to access the DOM element. The ElementRef enters the picture at this point.

Getting ElementRef in Component Class

To use the ElementRef to change the DOM, we must first obtain a reference to the DOM element in the component/directive.

To obtain the component's DOM element references

  1. Create a template reference variable for the component/element. directive's
  2. Using the ViewChild or ViewChildren, inject the element into the component class using the template variable.

To obtain the DOM element that houses the component/directive

  1. Angular will inject the reference element hosting the component/directive if you ask for ElementRef in the constructor (Angular-Dependency injection).

The variable hello, for example, relates to the HTML element div in the following code.

<div #hello>Hello Angular</div>

The Template Reference variable, hello, can be used in the Template.

The hello element is injected using the ViewChild in the Component class. The hello is injected as an ElementRef by Angular.

@ViewChild('hello', { static: false }) divHello: ElementRef;

Read token

Consider the following example.

<input #nameInput [(ngModel)]="name">

The input element is now bound to the nameInput Template Reference Variable. At the same time, we've applied the ngModel directive to it.

In this case, we can use the read token to inform Angular that we require an ElementRef reference, as illustrated below.

//ViewChild returns ElementRef i.e. input HTML Element
 
@ViewChild('nameInput',{static:false, read: ElementRef}) elRef;
 
 
//ViewChild returns NgModel associated with the nameInput
@ViewChild('nameInput',{static:false, read: NgModel}) inRef;

ElementRef Example

We may change the DOM using the nativeElement property after we obtain the ElementRef, as seen below.

import { Component,ElementRef, ViewChild, AfterViewInit } from '@angular/core';
 
@Component({
  selector: 'app-root',
  template:  '<div #hello>Hello</div>'
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
 
 @ViewChild('hello', { static: false }) divHello: ElementRef;
 
 ngAfterViewInit() {
   this.divHello.nativeElement.innerHTML = "Hello Angular";
 }
 
}

The DOM is fairly easy to alter.

ngAfterViewInit() {
  this.divHello.nativeElement.innerHTML = "Hello Angular";
  this.divHello.nativeElement.className="someClass";
  this.divHello.nativeElement.style.backgroundColor="red";
}

ElementRef in Custom Directive

The Angular directive is one of ElementRef's applications. In Angular, we learned how to make a custom directive. The code for the ttClass custom attribute directive is as follows.

import { Directive, ElementRef, Input, OnInit } from '@angular/core'
 
@Directive({
  selector: '[ttClass]',
})
export class ttClassDirective implements OnInit {
 
  @Input() ttClass: string;
 
  constructor(private el: ElementRef) {
  }
 
  ngOnInit() {
    this.el.nativeElement.classList.add(this.ttClass);
  }
 
}

It's worth noting that the ElementRef is injected in the constructor. When we ask for an ElementRef in the constructor, Angular will inject a reference to the directive's host DOM element.

ElementRef & XSS Injection Attack

An XSS Injection attack can occur if ElementRef is used incorrectly. For example, in the following code, we use the elementRef to inject a script. The script is run when the component that contains such code runs.

constructor(private elementRef: ElementRef) {
    const s = document.createElement('script');
    s.type = 'text/javascript';
    s.textContent = 'alert("Hello World")';
    this.elementRef.nativeElement.appendChild(s);
 }

Conclusion

In this article, we learned how to use ElementRef to get the reference of a HtmlElement and alter the DOM in Angular Applications.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post