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:
- Allows reading or modifying DOM element properties, such as
style,class,value. - 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:
ElementRefgives 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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.