ElementRef in Angular

ElementRef in Angular | Native Element

ElementRef is a wrapper around a native element inside of a View.

An ElementRef is backed by a render-specific element. In the browser, this is usually a DOM element.

Constructor -
constructor(nativeElementT)

Here nativeElement is parameter. The underlying native element or null if direct access to native elements is not supported.

Security risk on ElementRef -
Permitting direct access to the DOM can make your application more vulnerable to XSS attacks. Carefully review any use of ElementRef in your code. For more detail, seethe Security Guide.

class ElementRef<T> {
  constructor(nativeElementT)
  nativeElementT
}

Example ,
import { AfterContentInitComponentElementRef } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <h1>My Angular App</h1>
    <pre> <code>{{ name }}</code> </pre>
  `
})
export class AppComponent implements AfterContentInit {
  namestring;
  
  constructor(private elementRefElementRef) { }
  
  ngAfterContentInit() {
    const tmpEle = document.createElement('div');
    const el = this.elementRef.nativeElement.cloneNode(true);
    
    tmpEle.appendChild(el);
    this.name = tmpEle.innerHTML;
  }
}

ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^