Skip to main content

What does ElementRef do?

ElementRef in Angular is an object that provides direct access to the DOM element of a component or directive through the nativeElement property.

Usage:

  1. Allows reading or modifying DOM element properties, such as style, class, value.
  2. Used in directives to interact with the element they are applied to.

Example:

typescript
import { Component, ElementRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-example', template: `<p>Hello</p>` }) export class ExampleComponent implements AfterViewInit { constructor(private el: ElementRef) {} ngAfterViewInit() { this.el.nativeElement.style.color = 'red'; // change the text color } }

Conclusion: ElementRef gives direct access to the real DOM element, but its use should be limited to avoid violating Angular's principles and security (XSS).

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.