Skip to main content

What does ElementRef do?

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

Uses:

  1. Lets you read or change DOM element properties, for example 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 so as not to violate 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.